JQuery entry (b)

Jquery traversal

jQuery object itself is an array of objects obtained by the selector are satisfied jquery selector assembly of the condition of the element object, and therefore often necessary to traverse jquery object. There are three ways to traverse the Jquery.

 

Traditional loop through

var $options = $(“option”);
for(var i=0;i<$options.length;i++){
alert(option.value);
}

The method of jQuery object

This approach is unique to jQuery traversal using jQuery collection object to call each method can be traversed.
Syntax: jQuery objects .each (function (index, Element) {})
the each function argument: once per array traversal, call the anonymous function is the
anonymous function parameters: the index to traverse the array elements.

$ $ options = var ( "Option" ); 
$ options.each (function (index, Element) { 
Alert (index); // print index 
; Alert (Element) // each element $ options collection object print 
} );

Global jQuery method

This approach is unique jQuery traversal way above the jQuery object methods are similar, but here each method is not certain
, but each method, the names and functions of the global jQuery object, although the same concrete jQuery object, but the syntax is not
with.
Syntax:. $ Each (iterated array, function (index, element))

each function parameters: iterated array, may be jQuery object, the object may be a DOM

= $ options var $ ( "Option"); 
$ .each ($ options, function (index, Element) { 
Alert (index); // Print Index 
Alert (Element); // Print $ options each collection object element 
});
<Script type = "text / JavaScript"> 
$ (function () { 
/ *   
* embodiment 1: for loop mode 
* / 
var $ List = $ ( "# City Li" );
 for (var I = 0; I <$ List.length; I ++ ) {
 // iterate, DOM object properties call the innerHTML 
Alert ($ List [I] .innerHTML);
 // iterate, DOM object into a Jquery object method call HTML 
Alert ($ ($ List [I]) HTML ());. 
} 
       
      / * 
      * mode 2: each object's methods Jquery 
      * Jquery objects .each (function (index elements)) 
      * / 
      $ list.each (function (index, element) { 
     Alert (index + "---" + $ (Element) .html ()); 
     }); 
     
      / * 
      * mode 3: Jquery of each function 
      * $ .each (array, function (index elements)) 
      * / 
     $ .each ($ List, function (index, Element) {

    alert(index+"==="+$(element).html());
     });
      });
</script>

 

jQuery Events

Common events

jQuery event bindings with the solution to help event

Event binding function
jQuery object directly call the event functions, such as: $ ( "# the above mentioned id") the Click (function ()) {}.
ON (Events, Selector, the Data, the Fn) binding function

  Parameters events: event name, separate spaces between multiple events. "click mouseover"
  parameter selector: binding event element descendant elements, do not pass parameters, indicating that the binding elements of their own event
  parameter data: incident response parameters to be passed to the function
  parameters fn: function corresponding event

Bind button click event

$ ( "# btn") ON ( "the Click." , function () { 
  Alert ( "button click event ' ); 
});

Button binding multiple events

// same response function of multiple events, inflexible 
$ ( '# btn ") ON (" the Click mouseOver. " , Function () { 
  Alert ( " button click event' ); 
}); 
// Each event has its own response function 
$ ( "BTN #" ) .on ({
   "the click" : function () { 
    Alert ( "click event" ); 
 },
   "mouseOver" : function () { 
    Alert ( "hovers" ); 
 } 
} );

Progeny binding element for the event

// the above mentioned id value d2 is the offspring of the binding event element d1
 // If you have more offspring, separated by commas 
$ ( "# d1"). ON ( "the Click", "# d2" , function (the Data) { 
   Alert ( "D2 ..." ) 
});

off (events) unbind function
parameters: To release the event, multiple events separated spaces, do not pass parameter indicates the lifting of all events

$("#btn").click(function () {
  $("#d1").off("click mouseover");
});

Provinces linkage Case

<Script type = "text / JavaScript"> 
$ (function () { 
// definition area information 
var Areas = 
[ 
[ "Haidian District", "Changping District", "Chaoyang District"], // Representative Beijing 
[ "Nankai District "" zones of peace "," Xiqing District "], // Tianjin 
[" Pudong "," Puxi "," Minhang District "], // Shanghai 
[" xx zone "," yy area "," zz zone "] // Chongqing 
];
 // drop-down menu content changes the binding event 
$ ( '# City" ) .change (function () {
 // get the value of the selected option attribute value of 
var $ val = $ ( "# Option City: Selected " ) .val ();
 // get the array, the object becomes Jquery 
var $ Area = $ (Areas [$ Val]);
// add before emptying sub-tab 
$ ( "# Area" ) .empty (); 
$ ("#area") append ($ ( "<option> - Select area - </ option>." ));
 // iterate 
$ area.each (function (index, Element) {
 // create the option tags 
$ $ optionElement = var ( "<Option> </ Option>" ); 
$ optionElement.html (Element); 
// add to the province label 
$ ( "Area #" ) .append ($ optionElement); 
}); 
} ); 
/ * 
* another simplified written 
* / 
$ ( "#city" ) .change (function () {
 // get the value of the attribute value of the selected option 
var $ val = $ ( "# city option: selected" ) .val ();
 // get the array, the object becomes Jquery 
var $ area = $ (areas [ $ val]);

// define variable holds the string
var options = "<option> - select region - </ Option>";
$ area.each (function (index, Element) {
Options + = "<Option>" Element + + "< / Option> ";
});
$ (" Area # ") HTML (Options);.
});
});
</ Script>

Around elect Case

<Script of the type = "text / JavaScript"> 
$ (function () { 
// button to add a click event to bind
 // left selected, move to the right 
$ ( "# add" ) .click (function () {
 // get the right to obtain selected 
$ ( "# SECOND,") the append ($ ( "# First the Option: the selected." )); 
}); 
// button click event to bind addall
 // left all, move to the right 
$ ( "# add_all " ) .click (function () {
 // get the right to obtain all of the 
$ (" # SECOND, ") (the Option # First the append $ (." " )); 
}); 
$ ( " #remove " ) .click ( function () {
 // get the left to obtain the right to select the 
$ ( "# First") the append ($ ( "# SECOND, the Option: the selected." ));
});
$("#remove_all") .click (function () {
 // get the left to the right to obtain all 
$ ( "# first") append ($ ( "# second option")).;

});
});
</script>

 

Form validation plug
there were many mature widget user reference, jquery plug is to be used to achieve operation of the package, the package on the web
after the "small frame" can be called a plug, the plug according to the syntax may be implemented to operate a number of complex function, and we need
to do is learn how to use grammar to the plugin.
We only want to use is on form validation of jquery plugins.
Quick Start validate
find index.html under validate the demo directory. According to documents provided by the presentation, fast write your own validation.

<scripttype = "text / JavaScript"> 
$ (function () { 
     // Gets the id, the method calls the validate 
    $ ( "# empForm" ) .validate ({
       // definition of validation rules 
      the rules: {
         // text box attribute name must fill 
        realname: "required" 
      }, 
      // define authentication information 
      messages: {
         // textbox name property, violation of the rules of tips 
        realname: "really required name" 
      } 
    }); 
});
   </ Script>

Use Step
1. Download jquery-validation plug
2. The plug (i.e. a js file) into our project
3. js introduced into the html file to be used in the plug-in check

4. Preparation of Form validation code
$ ( "form Form selector") .validate ({
the rules: {
to which verifies name
table item name Found: validation rules, --- validation rule has been defined rule
table item name Found: validation rules ... ...
},
messages: {
single table name Found: error messages,
the table item name value: error message ... ...
}
});
common Validation rules

Custom form validation
Note: When an error message is not displayed in the position we thought, we can set a custom as follows
righteousness error is displayed on the label where we need to show that when this form item will not pass validation this information is automatically displayed
to, jquery validation plugin will automatically help us to control its display and hide
<lable for = "html element name value" class = "error" style = "display: none"> error message
</ lable>
if set the wrong lable labels do not have to set this table messages in a single error message

<script type="text/javascript">
    $(function(){
   
    //获取表单id,调用方法validate
   $("#empForm").validate({
   //定义验证规则
   rules:{
   //文本框的name属性,必须填写
   realname:"required",
   //用户名文本框验证,多个规则
   username:{
   //必须填写
   required:true,
   rangelength:[5,8]
   },
  
   //密码验证规则
   psw:{
   required:true,
   minlength:6,
   maxlength:12
   },
   //确认密码定义规则
   psw2:{
   required:true,
   minlength:6,
   maxlength:12,
   equalTo:"#psw"
   },
   //性别选择定义规则
   gender:{

 required:true
   },
   //年龄验证规则
   age:{
   required:true,
   range:[26,50]
   },
   //学历规则
   //由option标签的value属性决定
   edu:{
   required:true
   },
   //生日规则
   birthday:{
   required:true,
   //验证日期格式
   dateISO:true,
   //验证日期是否合法
   date:true
   },
   //兴趣爱好规则
   checkbox1:{
   required:true
   },
   //电子邮箱规则
   email:{
   required:true,
   email:true
   }
   },
   //定义验证信息
   messages:{
   //文本框name属性,违反规则的提示
   realname:"真是姓名必填",
   username:{
   required:"用户名必须填写",
   rangelength:"用户名5-8位"
   },
  
   psw:{
   required:"密码必须填写",
   minlength:"最小长度6",

  maxlength:"最大长度12"
    },
    
     psw2:{
   required:"确认密码必须填写",
   minlength:"最小长度6",
   maxlength:"最大长度12",
   equalTo:"两次密码不一致"
   },
   /*
   * 性别提示规则
   * 显示位置发生错误,手动在添加label标签
   */
   gender:{
   required:"请选择性别"
   },
  
   age:{
   required:"请输入年龄",
   range:"年龄在26-50之间"
   },
   edu:{
   required:"请选择一个学历"
   },
  
   birthday:{
   required:"请填写生日",
   dateISO:"日期格式不正确",
   date:"日期非法"
   },
   checkbox1:{
   required:"请选择至少一个爱好"
   },
   email:{
   required:"必须填写邮件",
   email:"请输入正确的邮件格式"
   }
   }
   });
    });
    </script>

自定义校验规则
如果预定义的校验规则尚不能满足需求的话可以进行自定义校验规则:
自定义校验规则步骤如下:
使用
$.validator.addMethod("**校验规则名称",function(value,element,params)){}**
在rules中通过校验规则名称使用校验规则
在messages中定义该规则对应的错误提示信息
其中: value是校验组件的value值
element是校验组件的节点对象
params是校验规则的参数

//身份证号规则
cart:{
  required:true,
  cartlength:[15,18],
  cart15:true,
  cart18:true
}
//参数: 规则名称. 参数 实现逻辑
   
//身份证号码长度
$.validator.addMethod( "cartlength", function(value,element,params){
  if(value.trim().length!=15 && value.trim().length!=18){
    return false;
  }
 return true;
 } );
   
//身份证号码15位校验
$.validator.addMethod( "cart15", function(value,element,params){
    //定义15位正则规则,必须全部数字
    var reg = /^[0-9]{15}$/;
    if(value.trim().length==15){
      return reg.test(value.trim());
}
    return true;
 } );
   
//身份证号码18位校验
$.validator.addMethod( "cart18", function(value,element,params){
    //定义15位正则规则,必须全部数字
    var reg = /^[0-9]{18}|[0-9]{17}X$/;
    if(value.trim().length==18){
      return reg.test(value.trim());
   }
    return true;
} );

 

Guess you like

Origin www.cnblogs.com/qingmuchuanqi48/p/11129723.html