文章目录
*在业务需求中遇到jQuery中没有的方法,可以使用extend()方法自己扩展
jQuery插件扩展的两种方式(全局): $.extend()
扩展给jQuery本身,使用时可以直接调用
扩展完成后只能用$.方法名或jQuery.方法名来调用
jQuery.extend提供一个参数,这个参数是一个对象,对象中包含要扩展的方法
使用场景:当某段可实现一些功能的代码需要多次调用,可以扩展成一个函数,提高复用性
格式:(给jQuery添加扩展)
$.extend({//定义
方法名: function () {
console.log("你好世界");
}
});
$.方法名();//调用
示例:扩展min和max两个方法给jQuery本身
// 定义一个min和max到jQuery全局对象中
$.extend({
min(a, b) { return a < b ? a : b;},
max(a, b) {return a > b ? a : b;}
});
// 调用这个自定义方法
var big = $.max(3 * 3 * 3, 2 * 2 * 2 * 2 * 2);
console.log(big); //32
jQuery插件扩展的两种方式(局部): $.fn.extend()
扩展元素集,需要创建对象才能使用
扩展完成后给元素的集合使用,
这里元素的集合是指如$("ul>li")选择器获取到的元素的集合
同样地,
$.fn.extend 提供一个参数,这个参数是一个对象,对象里面是用户自己扩展的方法
使用场景:处理jQuery对象时,需要对jQuery对象直接处理
格式:(给jQuery对象添加扩展)
$.fn.extend({//定义
方法名: function () {
console.log("你好世界");
}
})
$(元素集合).方法名()//调用
示例:扩展一个输出复选框的value信息的方法vals()
<input type="checkbox" onclick="t()" value="我是复选框">点击选中
<script>
jQuery.fn.extend({
vals: function(result) {
this.each(function() { //jquery.each()方法遍历指定对象或数组
if (this.checked) {
result = result + "," + this.value
}
});
return result;
}
})
function t() {
var result = $("input").vals("hello"); //调用vals()
console.log(result);
}
结果
在拓展方法后面添加css会失效和解决方法
代码
<button>点击</button>
<div id="box"></div>
<script>
$.extend($.fn, {
allCheck(ischeck) {
this.prop("checked:", ischeck);
}
})
$("button").click(function() {
$("div").css({
width: 100,
height: 30,
background: "red"
}).allCheck(true)
});
</script>
结果
此处allCheck(true)
不能放在css()之前否则报错:
Uncaught TypeError:
Cannot read properties of undefined (reading 'css')
解决方法
在自定义方法中返回this后,可以让css放在后面
<button>点击</button>
<div id="box"></div>
<script>
$.extend($.fn, {
allCheck(ischeck) {
this.prop("checked:", ischeck);
return this;//返回this
}
})
$("button").click(function() {
$("div").allCheck(true).css({
width: 100,
height: 30,
background: "red"
})
});
</script>