jQuery UI和事件处理 [英] JQuery UI and event handling

查看:132
本文介绍了jQuery UI和事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery UI小部件,它附加到div上,然后侦听其中的特定控件(通过选项设置).问题在于,在我的事件侦听器中,这是指更改的控件,而不是小部件所附加的元素.那么如何访问小部件元素?

I have a jQuery UI widget which attaches to a div and then listens to specific controls inside it (set via options). The problem is that in my event listener, this refers to the control that changed, not the element the widget is attached to. So how can I access the widget element?

    _addressChanged: function () {
        $(this).data("address").requiresValidation = true;
    },

    _bindEventHandlers: function () {
        $(this.options.address1).bind("change", this._addressChanged);
        $(this.options.address2).bind("change", this._addressChanged);
        $(this.options.city).bind("change", this._addressChanged);
        $(this.options.zip).bind("change", this._addressChanged);
    },

推荐答案

使用 this._on()方法绑定处理程序.此方法由jQuery UI小部件工厂提供,并将确保在处理函数中,this始终引用小部件实例.

Use the this._on() method to bind the handler. This method is provided by the jQuery UI widget factory and will make sure that within the handler function, this always refers to the widget instance.

_bindEventHandlers: function () {
    this._on(this.options.address1, {
        change: "_addressChanged" // Note: pass the function name as a string!
    });
    ...
},
_addressChanged: function (event) {
    // 'this' is now the widget instance.
    // 'this.element', as suggested by sjsharktank, is the DOM element the widget was created on
},

这篇关于jQuery UI和事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆