This article mainly introduces code examples for modifying or extending jQuery native methods. This article uses an example of extending jquery native method val to explain how to modify or extend jquery native methods. Friends who need it can refer to it
Modify or extend jQuery method code examples:
There is no doubt that jQuery is a powerful and easy-to-use class library.
Its wide application can confirm the above point of view, but as the saying goes, no one is perfect, and no gold is perfect. The same is true for jQuery. It cannot complete our tasks perfectly at any time or occasion, so In the future, the original methods of jQuery will need to be extended and modified, but the best method still has the original functions.
Code example:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>php中文网</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> </head> <body> <span id="lbl">php中文网</span> <input type="text" id="txt" value="softwhy.com" /> <input type="checkbox" value="antzone" /> <p id="show"></p> </body> </html>
The above code is undoubtedly an extension of jQuery’s val() method. Here is an introduction to its implementation process.
Code comments:
1. $.prototype.val = function (base) {}(($.prototype.val), modify jQuery’s original val() method, and use closure here In the package method, the parameter passed is the original val() method to maintain the function of the original val() method. 2. return function (){}, returns a function object. >3. var s = this, assign the reference of this to variable s, where this points to the jQuery object instance. 4. var a = "data-property", declare a variable and assign a value. , more content about it will be introduced later.
5. var p = s.attr(a). In fact, data-property is a custom attribute on the label, so this code is to obtain the value of this attribute. .
6. var isset = arguments.length > 0, determine whether the modified val() method passes parameters.
7. var v = isset ? arguments[0]: null, if a parameter is passed, the first parameter will be obtained, and the others will be ignored. 8. if (isset&&typeof(base)=="function") { base.call(s, v);}, If parameters are passed and the base parameter is a function, then the base function is called to set the element
The above is the entire content of this chapter. For more related tutorials, please visit
jQuery video tutorial! >