To create a global function, you only need to add attributes to the jquery object. You can also create a jquery object by adding attributes to the jquery object. in fact, jquery. the fn object is jquery. the alias of the prototype object.
Demo:
Copy codeThe Code is as follows:
JQuery. fn. test = function (){
Alert ('this is the jquery object method ');
}
Then, you can call this method in any jquery object.
Copy codeThe Code is as follows:
$ (Function (){
$('H1 '). click (function (){
$ (This). test ();
});
});
As there is no match for the dom node here, it is also possible to write a global function (as mentioned in the previous section). However, when using the jquery object method, the this keyword in the function always references the current jquery object. Therefore, we can rewrite the above method to implement dynamic prompt information. The Code is as follows:
Copy codeThe Code is as follows:
JQuery. fn. test = function (){
Alert (this [0]. nodeName); // prompt the dom node name of the current jquery object
}
In the preceding example, we can see that because the jquery selector returns an array-type dom node set, this pointer points to the current set, so the node name of the current element must be displayed, the sequence number of the current element must be specified after the this pointer.
Thinking: If the jquery selector matches multiple elements, how can we accurately specify the object of the current element? -----
To solve this problem, we may call the each () method in the current jquery object method environment and use the implicit iteration method to let this pointer consume each matching dom Element Object in sequence, for example, make further modifications to the previous example.
Copy codeThe Code is as follows:
JQuery. fn. test = function (){
This. each (function () {// traverses matched elements. this indicates the object set.
Alert (this. nodeName); // prompt the dom node name of the current jquery object (note the changes here and above, and the subscript disappears)
});
}
Then, when calling a method, you don't have to worry about the number of elements that the jquery selector matches. For example, in the following example, When you click different elements, the current node name is displayed.
Copy codeThe Code is as follows:
$ (Function (){
$ ('Body * '). click (function (){
$ (This). test ();
});
});
Copy codeThe Code is as follows:
<H1> ceshi <A> dddddddddd </a>
<Input type = "button" value = "test"/>
<Div> div element </div>