1

我无法将自定义事件添加到 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对象上附加/触发事件,但我想触发附加到我的插件实例的事件。这不可能吗?

提前致谢。

4

2 回答 2

4

一些代码修改及其工作

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

试试下面

 triggerChange : function () {

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


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

http://jsfiddle.net/FhqNf/3/

于 2013-05-12T08:30:57.893 回答
2

您需要链接来触发自定义事件,然后让链接侦听自定义事件。

您的插件没有返回 jQuery 对象,因此尝试将.on函数链接到 null 返回不会做任何事情。尝试使用链接 ID 或返回对象以保持函数链接正常工作。

我将其更改为:

link.trigger('mycustomevent');
$("#test1").on('mycustomevent'....);

小提琴:http: //jsfiddle.net/FhqNf/4/

于 2013-05-12T08:31:59.850 回答