0
jQuery.widget("ui.test",{
    _init: function(){
        $(this.element).click(this.showPoint);
    },

    showPoint: function(E){
        E.stopPropagation();
        alert(this.options.dir);
    }
}

$('#someEleme').test();

现在,我编写options对象的方式未在 showPoint
事件处理程序中定义。在 jQuery 小部件中传递这个值的正确方法是什么?

4

1 回答 1

1

它与showPoint调用函数的上下文有关。在您的情况下,您已将函数提供给 jQuery 事件处理程序,这会导致 jQuery 在 event.target 元素的上下文中调用该函数。您可以使用 覆盖它jQuery.proxy(),在您的代码中,它看起来像这样:

jQuery.widget("ui.test",{
    _init: function(){
        $(this.element).click($.proxy(this.showPoint, this));
    },

    showPoint: function(E){
        E.stopPropagation();
        alert(this.options.dir);
    }
}

请注意,这将覆盖thisshowPoint 函数中的变量,因此您不能再使用类似的东西$(this).hide(),您将不得不使用$(E.target).hide()or 事实上$(this.element).hide()

于 2012-01-28T22:26:39.387 回答