欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

巧用jQuery選擇器提高寫表單效率的方法

 更新時(shí)間:2016年08月19日 11:30:03   作者:violetjack0808  
這篇文章主要教大家如何巧用jQuery選擇器提高寫表單效率的方法,感興趣的小伙伴們可以參考一下

相信很多小伙伴都會(huì)遇到需要做表單的需求,就像我現(xiàn)在做的醫(yī)院項(xiàng)目,茫茫多的表單無窮無盡。一開始做表單使用最笨的方法:一個(gè)個(gè)span去定義ID,每個(gè)數(shù)據(jù)都用ajax獲取后賦值顯示,然后在表單提交前一個(gè)個(gè)用jQuery根據(jù)ID獲取元素的value,組成一個(gè)model來提交給服務(wù)器。
后來發(fā)現(xiàn)使用jQuery可以大大簡(jiǎn)化這個(gè)過程。于是我修改了工作方法,總結(jié)了我的一些提高寫表單效率的方法。 

需求

表單中存在最多的無非就是文本、文本框、單選框、多選框。而一些表單中會(huì)有幾十個(gè)甚至幾百個(gè)選項(xiàng)。我們的目標(biāo)就是以最高的效率來完成這些表單的數(shù)據(jù)獲取和數(shù)據(jù)提交。
注意:如果元素ID和服務(wù)器上獲取的json字段的名字是一樣的,那么這篇文章或許能對(duì)你提高工作效率有所幫助。

文本和文本框

對(duì)于文本和文本框,我們通常需要為元素添加ID來綁定和獲取數(shù)據(jù)。

將數(shù)據(jù)顯示到界面中
 •用for循環(huán)遍歷解析成功的JSON數(shù)據(jù)
 •通過if判斷過濾數(shù)據(jù)是span的還是input的。
 •將數(shù)據(jù)傳給和數(shù)據(jù)名同名的ID元素。

 for (var key in json) {
  //過濾type為text的文本框
  if ($('#' + key).attr('type') == 'text') {
    $('#' + key).val(json[key]);
  }
  if($('#' + key).prop('tagName') == 'SPAN'){
    $('#' + key).text(json[key]);
  }
}

快速獲取數(shù)據(jù)對(duì)象用于提交服務(wù)器
 •定義空model對(duì)象。
 •通過jQuery選擇器獲取目標(biāo)元素的value。
 •將數(shù)據(jù)傳入model中,對(duì)象元素的字段就是HTML元素的ID。 

var model = {};
$('input[type="text"]').each(function () {
  model[$(this).attr('id')]=$(this).val();
});
$('span').each(function () {
  model[$(this).attr('id')]=$(this).text();
});
console.log(model);

按照如下方法,我們只需要照著后端提供的數(shù)據(jù)字段給HTML定義id,而JS就不需要寫太多代碼就可以完成表單了。再也不怕表單字段太多了。

全部代碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="jquery-2.2.3.js"></script>
</head>
<body>
  <div>
    <div>
      <label>姓名:<input type="text" id="name"></label>
      <label>性別:<input type="text" id="sex"></label>
      <label>年齡:<input type="text" id="age"></label>
      <label>時(shí)間:<input type="text" id="time"></label>
    </div>
    <div>
      <label>a:<span id="param01">1</span></label>
      <label>b:<span id="param02">2</span></label>
      <label>c:<span id="param03">3</span></label>
      <label>d:<span id="param04">4</span></label>
    </div>
  </div>
  <button onclick="showResult()">顯示結(jié)果</button>
  <script>
    //多條input或者span的快速賦值
    //data是模擬服務(wù)器返回的JSON數(shù)據(jù)
    var data = '{"name":"張三","sex":"女","age":22,"time":"2016-5-10","param01":111,"param02":222,"param03":333,"param04":444}';
    //將數(shù)據(jù)顯示到頁(yè)面中
    var json = eval('(' + data + ')');
    for (var key in json) {
      if ($('#' + key).attr('type') == 'text') {
        $('#' + key).val(json[key]);
      }
      if($('#' + key).prop('tagName') == 'SPAN'){
        $('#' + key).text(json[key]);
      }
    }

    //獲取文本和文本框的內(nèi)容轉(zhuǎn)為JSON對(duì)象
    function showResult() {
      var model = {};
      $('input[type="text"]').each(function () {
        model[$(this).attr('id')]=$(this).val();
      });
      $('span').each(function () {
        model[$(this).attr('id')]=$(this).text();
      });
      console.log(model);
    }
  </script>
</body>
</html>

Radio和Checkbox

另外一種經(jīng)常出現(xiàn)于表單中的就是radio、checkbox這些單選多選的元素了。這些元素通常用name命名一組選項(xiàng)。下面我同樣用jQuery簡(jiǎn)化數(shù)據(jù)的顯示和提交。

顯示數(shù)據(jù)

和之前的文本一樣,用for循環(huán)遍歷json數(shù)據(jù),然后通過if過濾后顯示到界面。不同之處是這邊是通過name來顯示和綁定數(shù)據(jù)的。
注:對(duì)radio和checkbox處理的方法寫在了后面,所以復(fù)制粘貼的同學(xué)們請(qǐng)注意別漏了~

for(var key in json){
  if ($('input[name=' + key + ']').attr('type') == 'radio') {
   showRadioValue(key, json[key]);
  }
  if ($('input[name=' + key + ']').attr('type') == 'checkbox') {
   showCheckBoxValue(key, json[key]);
  }
}

獲取數(shù)據(jù)model的方法
 •定義空model對(duì)象。
 •定義name避免重復(fù)添加。
 •遍歷所有radio獲取結(jié)果傳給model
 •遍歷所有checkbox獲取結(jié)果傳給model

     function showResult() {
      var model = {};
      var radioName = '';
      var checkboxName = '';
      $("input[type='radio']").each(function () {
        if($(this).attr('name') != radioName){
          radioName = $(this).attr('name');
          model[radioName] = getRadioValue(radioName);
        }
      });
      $("input[type='checkbox']").each(function () {
        if($(this).attr('name') != checkboxName){
          checkboxName = $(this).attr('name');
          model[checkboxName] = getCheckboxValue(checkboxName);
        }
      });
      console.log(model);
    }

處理radio和checkbox的一些方法

這里我對(duì)radio和checkbox的顯示和獲取結(jié)果寫了幾個(gè)方法。

    function showRadioValue(name, value) {
      $('input[name=' + name + ']').each(function () {
        if(value == $(this).val()){
          $(this).attr('checked', 'true');
        }
      });
    }

    function getRadioValue(name) {
      var value = 0;
      var i = 0;
      $('input[name=' + name + ']' ).each(function () {
        if ($('input[name=' + name + ']').eq(i).is( ':checked')) {
          value = $('input[name=' + name + ']').eq(i).val();
          return;
        }
        i++;
      });
      return value;
    }

    function showCheckBoxValue (name, value) {
      var values = value.split(',' );
      var row = 1;
      $('input[name="' + name + '"]').each( function () {
        if (values[row] == 1) {
          $(this).attr("checked" , 'true');
        }
        row++;
      });
    }

    function getCheckboxValue (name) {
      var text = "" ;
      $('input[name="' + name + '"]').each( function () {
        var t = '' ;
        if ($(this ).is(':checked')) {
          t = "1";
        } else {
          t = "0";
        }
        text += "," + t;
      });
      return text;
    }

代碼

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script src="jquery-2.2.3.js"></script>
</head>
<body>
 <div>
  <div>
   <label><input type="radio" name="param01" value="1">1</label>
   <label><input type="radio" name="param01" value="2">2</label>
   <label><input type="radio" name="param01" value="3">3</label>
  </div>
  <div>
   <label><input type="radio" name="param02" value="1">1</label>
   <label><input type="radio" name="param02" value="2">2</label>
   <label><input type="radio" name="param02" value="3">3</label>
  </div>
  <div>
   <label><input type="radio" name="param03" value="1">1</label>
   <label><input type="radio" name="param03" value="2">2</label>
   <label><input type="radio" name="param03" value="3">3</label>
  </div>
  <div>
   <label><input type="checkbox" name="param04">1</label>
   <label><input type="checkbox" name="param04">2</label>
   <label><input type="checkbox" name="param04">3</label>
   <label><input type="checkbox" name="param04">3</label>
  </div>
  <div>
   <label><input type="checkbox" name="param05">1</label>
   <label><input type="checkbox" name="param05">2</label>
   <label><input type="checkbox" name="param05">3</label>
   <label><input type="checkbox" name="param05">3</label>
  </div>
  <button onclick="showResult()">顯示結(jié)果</button>
  <label id="result">result</label>
 </div>
 <script>
  //多條radio或者checkbox的快速賦值
  var data = '{"param01":"1","param02":"3","param03":"2","param04":",1,0,0,0","param05":",0,0,1,1"}';
  var json =eval( '(' + data + ')');
  for(var key in json){
   if ($('input[name=' + key + ']').attr('type') == 'radio') {
    showRadioValue(key, json[key]);
   }
   if ($('input[name=' + key + ']').attr('type') == 'checkbox') {
    showCheckBoxValue(key, json[key]);
   }
  }

  function showRadioValue(name, value) {
   $('input[name=' + name + ']').each(function () {
    if(value == $(this).val()){
     $(this).attr('checked', 'true');
    }
   });
  }

  function getRadioValue(name) {
   var value = 0;
   var i = 0;
   $('input[name=' + name + ']' ).each(function () {
    if ($('input[name=' + name + ']').eq(i).is( ':checked')) {
     value = $('input[name=' + name + ']').eq(i).val();
     return;
    }
    i++;
   });
   return value;
  }

  function showCheckBoxValue (name, value) {
   var values = value.split(',' );
   var row = 1;
   $('input[name="' + name + '"]').each( function () {
    if (values[row] == 1) {
     $(this).attr("checked" , 'true');
    }
    row++;
   });
  }

  function getCheckboxValue (name) {
   var text = "" ;
   $('input[name="' + name + '"]').each( function () {
    var t = '' ;
    if ($(this ).is(':checked')) {
     t = "1";
    } else {
     t = "0";
    }
    text += "," + t;
   });
   return text;
  }

  function showResult() {
   var model = {};
   var radioName = '';
   var checkboxName = '';
   $("input[type='radio']").each(function () {
    if($(this).attr('name') != radioName){
     radioName = $(this).attr('name');
     model[radioName] = getRadioValue(radioName);
    }
   });
   $("input[type='checkbox']").each(function () {
    if($(this).attr('name') != checkboxName){
     checkboxName = $(this).attr('name');
     model[checkboxName] = getCheckboxValue(checkboxName);
    }
   });
   console.log(model);
  }
 </script>
</body>
</html>

Tips
 •如果有一些特殊處理的內(nèi)容(如時(shí)間格式文本),可以先遍歷后在遍歷之后單獨(dú)進(jìn)行賦值。
 •以上方法可以用于所有以ID定義的用于顯示和獲取數(shù)據(jù)的HTML元素。
 •用好jQuery的選擇器可以獲取到任何所需的元素、元素集合。
 •在each()方法中$(this)表示當(dāng)前元素。
 •獲取所選ID的元素標(biāo)簽:$('#' + key).prop('tagName') == 'SPAN',注意:標(biāo)簽結(jié)果'SPAN'都是大寫的,可以打log驗(yàn)證。
 •不斷找規(guī)律、總結(jié)提煉,找出最好的偷懶方法,盡量避免體力勞動(dòng)。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論