1、使用 $.fn 可以扩展 jQuery 对象的原型,从而为 jQuery 对象添加新的方法或属性。
<div class="container">
<button>点击</button>
</div>
<script>
$.fn.changeColor = function(color) {
this.css('background-color', color);
return this;
};
$('button').click(function() {
$('.container').changeColor('red');
});
</script>
上述代码表示:使用 $.fn 扩展 jQuery 对象的原型,为 jQuery 对象添加了一个新的方法 changeColor(),该方法可以改变调用它的元素的背景颜色。然后在页面加载完成后,给 button 元素绑定一个点击事件,触发该事件时,调用 changeColor() 方法改变 container 元素的背景颜色为红色。
2、使用 $.extend 可以扩展 jQuery 对象本身,从而为 jQuery 对象添加新的方法或属性。
<div id="container"></div>
<script>
$.extend({
sayHello: function(name) {
$('#container').text('Hello, ' + name + '!');
}
});
$.sayHello('John');
</script>
上述代码表示:使用 $.extend 扩展 jQuery 对象,为 jQuery 对象添加一个新的方法 sayHello(),该方法可以根据传入的参数向指定的元素输出问候语。然后调用 $.sayHello('John') 方法,将 container 元素的内容改变为 Hello, John!。