定义函数时出现$(this)问题



我有这个代码来删除表行选择。(小提琴)

$('select').change(function() {
     var $this = $(this),
            list = $('table tbody tr'),
            findoption = $this.find('option:selected'),
            selected = findoption.data('hide'),
            show_hide_li = $this.find("."+selected);
        if (selected == "reset") {
            list.show();
        }
        else  {
           $('.'+selected).show();
            list.not('.'+selected).hide()
        }   
});

当我将代码移出change function并像下面这样定义它时,我遇到了一个问题,即$(this)会阻止代码工作。谁能告诉我如何定义一个函数时,有$(this)在代码?

var cancel = function(){
     var $this = $(this),
            list = $('table tbody tr'),
            findoption = $this.find('option:selected'),
            selected = findoption.data('hide'),
            show_hide_li = $this.find("."+selected);
        if (selected == "reset") {
            list.show();
        }
        else  {
           $('.'+selected).show();
            list.not('.'+selected).hide()
        }           
}

$('select').change(function() {
       cancel();
    });

我认为这就是你想要做的。

function cancel(){
     var $this = $(this),
            list = $('table tbody tr'),
            findoption = $this.find('option:selected'),
            selected = findoption.data('hide'),
            show_hide_li = $this.find("."+selected);
        if (selected == "reset") {
            list.show();
        }
        else  {
           $('.'+selected).show();
            list.not('.'+selected).hide()
        }           
}

$('select').change(cancel);

您可以将"this"作为参数传递给函数

var cancel = function(param1){
     var $this = $(param1),
            list = $('table tbody tr'),
            findoption = $this.find('option:selected'),
            selected = findoption.data('hide'),
                show_hide_li = $this.find("."+selected);
        if (selected == "reset") {
            list.show();
        }
        else  {
           $('.'+selected).show();
            list.not('.'+selected).hide()
        }           
}

$('select').change(function() {
       cancel(this);
});

使用jquery的.on方法

$('select').on('change', cancel);
var cancel = function(){
    var $this = $(this),
        list = $('table tbody tr'),
        findoption = $this.find('option:selected'),
        selected = findoption.data('hide'),
        show_hide_li = $this.find("."+selected);
        if (selected == "reset") {
            list.show();
        }
        else  {
            $('.'+selected).show();
            list.not('.'+selected).hide()
        }           
}

这行非常简短,但功能强大,应该取代后面显示的内容:

$('select').change(cancel);

用上面的行代替下面的行:

$('select').change(function() {
       cancel();
});

因为这三行相当于:

$('select').change(function() {
       //you have access to 'this' here
       function() {
             //your body
       }
});

正如你所看到的,内部函数不能访问this,除非你显式地将其作为参数传递,这可以通过删除嵌套函数来轻松避免。

最新更新