Modify or Extend jquery's method code example:
There is no doubt that jquery is a powerful and easy to use class library.
From its wide application can confirm the above point of view, but the so-called no one is perfect, gold without pure, jquery is also so, not at any time or occasion can complete our task, so something will need to the original jquery methods to extend the modification, But the best method still has the original function.
Code instance:
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title> Cloud-dwelling community </title>
<script src= "Http://libs.baidu.com/jquery/1.9.0/jquery.js" ></script>
<script>
$.prototype.val = function (base) {
return function () {
var s = this;
var a = "Data-property";
var p = s.attr (a);
var isset = arguments.length > 0;
var v = isset? ARGUMENTS[0]: null;
if (isset&&typeof (base) = = "function") {
Base.call (S, v);
}
else {
v = base.call (s);
}
if (p) {
if (isset) {
S.attr (P, v);
return s
}
else {
Return S.attr (P)
}
}
else {
if (!s.is (": Input")) {
if (isset) {
S.text (v); return s;
}
else {
return S.text ();
}
}
else {
Return isset? S:v;
}
}
}
} ($.prototype.val);
$ (document). Ready (function () {
$ ("#show"). HTML ($ ("#lbl"). Val () + "<br>" +$ ("#txt"). Val ());
})
</script>
<body>
<span id= "LBL" > Cloud-dwelling Community </span>
<input type= "text" id= "TXT" value= "softwhy.com"/>
<input type= "checkbox" value= "Antzone"/>
<div id= "Show" ></div>
</body>
The above code is no doubt an extension of the Val () method of jquery, and here's how it's implemented.
Code comments:
1.$.prototype.val = function (base) {} ($.prototype.val) modifies the original Val () method of jquery, which takes the form of closures, passing arguments that are the original Val () method to keep the original Val () The functionality of the method.
2.return function () {}, returns a function object.
3.var s = This, assigns this point reference to the variable s, where this is pointing to the JQuery object instance.
4.var a = "Data-property" declares a variable and assigns a value, which is described in more detail about it.
5.var p = s.attr (a), in fact Data-property is a custom attribute on the label, then this code is to get this property value.
6.var isset = arguments.length > 0 To determine whether the modified Val () method passed parameters.
7.var v = isset Arguments[0]: null, if the parameter is passed, so long get the first argument, the other ignored.
8.if (isset&&typeof (base) = = "function") {
Base.call (S, v);
}, if the parameter is passed and the base parameter is a function, Then call the base function setting element