根据我们的需要有时候会扩展$实例方法,eg: $("#id").customFunction
这里需要用到 jquery 内置的$.fn.extend方法,有关$.fn.extend请参考http://blog.csdn.net/trifling_/article/details/69666977
总体结构
(function($) {
$.fn.extend({
customFunction: function(options) {
...// 自定义方法,比方复杂的则需提出去单独写,再此引用比较优雅
}
});
})(jQuery);
eg : 扩展jquery实例的parentName, 获取父节点的name
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="index.css" > <script src="jquery-3.2.1.js"></script> <script src="getParentName.js"></script> </head> <body> <div name = "this is parent"> <div id="child" name ="this is child"> </div> </div> <span id="data"></span> </body> <script> $("#data").text($("#child").getParentName()); </script> </html>
getParentName.js
(function($) { $.fn.extend({ getParentName: function() { return this.parent().attr("name"); } }); })(jQuery);结果: 页面展示 this is parent