jQuery中启动/更改的单选按钮设置功能相同



我有一个共享的jQuery函数,它检查RadioButton的选择:如果选择了1,它会隐藏一个跨度,否则会显示它。

这个共享函数在启动和更改时都被调用,因为在启动时,它需要做同样的事情。启动有效,但onChange引用无效:

JS_OBJ = {
    toggleTier : function() {
        if ($('input[name="tier"]:checked').val() == 'Y_YES')
        {
            $('#tierSpan').hide();
        }
        else
        {
            $('#tierSpan').show();
        }       
    },
    // this is called from document.onReady - it comes here, OK
    onReady : function() {      
        // on startup, toggle Tier - works OK
        this.toggleTier();
        // Also link the radio button Change to this shared function
        $('input[name="tier"]:radio').change(function () {
            alert('About to enter toggle...');
            // NEVER COMES HERE - Object doesn't support this property or method
            this.toggleTier(); 
        });
    }
};

this在通过不同区域时正在更改值。当它第一次被实例化时,它有一个很好的值,但单选按钮:change有一个不同的this

我能够改变它,让它发挥作用:

    $('input[name="tier"]:radio').change(function () {
        alert('About to enter toggle...');
        self;   //closure
        toggleTier(); 
    });

看看这个:这个JavaScript习惯用法的基础是什么:var self=this?

更改事件内部,不是指当前的JS_OBJ,而是指当前的事件目标。您希望显式保存对this的引用,以便在事件中使用它。

示例:

onReady : function() {      
    var me = this;
    me.toggleTier();
    // Also link the radio button Change to this shared function
    $('input[name="tier"]:radio').change(function () {
        me.toggleTier(); 
    });
}

最新更新