gpt4 book ai didi

jquery - jQuery 插件实例上的自定义事件触发器

转载 作者:行者123 更新时间:2023-12-01 06:35:48 25 4
gpt4 key购买 nike

我在向 jQuery 插件添加自定义事件时遇到问题。

我制作了一个非常简单的 jQuery 插件,从中触发一个事件,但附加的处理程序无法正确触发:http://jsfiddle.net/FhqNf/2/

(function($) {

var my_plugin = function(link, opts) {

var $this = this, img, o={};

defaults = {
color: 'rgb(255, 0, 0)'
};

$.extend(this, $.fn, {
init : function () {
o = $.extend(defaults, opts);
link.on('click', $this.changeColor);
},

changeColor : function (e) {
if( link.css('color') == o.color)
link.css('color', 'blue');
else
link.css('color', o.color);

$this.triggerChange();
},

triggerChange : function () {
$this.triggerHandler('custom', {test: 'ok', color: o.color} );
}
});

this.init();

};

$.fn.my_plugin = function(opts) {
return new my_plugin(this, opts);
};

然后,如果我使用我的插件并将函数附加到我的“自定义”事件处理程序,则该事件不会触发:

var test1 = $('#test1').my_plugin();
test1.on('custom', function (data) { console.log(data); alert('test1') } );

编辑:解决方法是在“链接”dom 对象上附加/触发事件,但我想触发附加到我的插件实例的事件。这不可能吗?

提前致谢。

最佳答案

一些代码修改及其工作

在您的代码中,您在不同对象上触发事件并将处理程序附加到不同对象。

尝试下面

 triggerChange : function () {

link.trigger('custom', {test: 'ok'} );
}


$.fn.my_plugin = function(opts) {
new my_plugin(this, opts);
return this;
};

<强> http://jsfiddle.net/FhqNf/3/

关于jquery - jQuery 插件实例上的自定义事件触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com