一旦应用jquery插件默认选项修改
以下面的插件为例:一旦应用jquery插件默认选项修改,jquery,Jquery,以下面的插件为例: (function($) { $.fn.alertOnClick = function(text) { return this.each(function(){ $(this).click(alert(text)); }); } })(jQuery); 我可以这样使用: $('p').alertOnClick("this is a silly plugin"); $("p").not("#p1").a
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).click(alert(text));
});
}
})(jQuery);
我可以这样使用:
$('p').alertOnClick("this is a silly plugin");
$("p").not("#p1").alertOnClick("Hello");
$("#p1").alertOnClick("Bye");
如何修改插件代码以支持执行以下操作:
$('p').alertOnClick("this is a silly plugin");
$('p#someSpecificP').setAlertText("different alert text");
这会产生这样的效果,即所有的p
在单击时都会显示“这是一个愚蠢的插件”
,除了id为“SomeSpecific p”
的p
会显示“不同的警报文本”
这个例子显然不是我真正的代码,而是一个类比。我有一个插件应用于许多默认元素。在页面的生命周期中,我可能想更改应用插件的单个元素的一些默认设置,但不是全部
谢谢我还没有尝试过,但您应该能够定义一个成员函数,类似于:
(function($) {
$.fn.alertOnClick = function(text) {
setAlertText: function(newText) {
$(this).click(alert(newText));
}
return this.each(function(){
$(this).click(alert(text));
});
}
})(jQuery);
为什么不这样做:
$('p').alertOnClick("this is a silly plugin");
$("p").not("#p1").alertOnClick("Hello");
$("#p1").alertOnClick("Bye");
在元素上再次调用alertOnClick有效。只需记住解除所有单击事件的绑定,然后应用新事件。测试1
<p>test 1</p>
<p>test 2</p>
<p id="s1">test 3</p>
<p>test 4</p>
<script type="text/javascript">
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).unbind('click');
$(this).bind('click', {'t' : text}, function(e){
alert(e.data.t);
});
});
}
})(jQuery);
$('p').alertOnClick('common alert');
$('p#s1').alertOnClick('unique alert');
</script>
测试2
测试3
测试4
(函数($){
$.fn.alertOnClick=函数(文本){
返回此值。每个(函数(){
$(this.unbind('click');
$(this.bind('click',{'t':text},函数(e){
警报(e.data.t);
});
});
}
})(jQuery);
$('p').alertOnClick('common alert');
$('p#s1').alertOnClick('unique alert');
这对我来说很好。我刚刚从目标元素中解除了先前绑定事件的绑定。使用data()
解决了它,但不确定这是否是最好的方法
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).data('alertText', text).click(function(){
alert($(this).data('alertText'));
});
});
}
$.fn.setAlertText = function(text) {
return this.data('alertText', text);
}
})(jQuery);
当我第一次分配“hello”时,我不知道什么是
#p1
,所以我不能用not
排除它。因此,再次调用同一个函数只需附加两次事件侦听器:(这将使它对两条消息都发出警报。我更喜欢不干扰其他代码的解决方案(即,您的代码从我的元素中删除所有单击事件侦听器,无论它们是否与alertOnClick有关)那个么,也许解决方案是将所有标记的元素存储在某个数组及其参数(警报字符串)中。每个函数调用都将扩展现有数组及其参数。。。