原型这个选择器

时间:2012-05-13 08:08:13

标签: javascript jquery prototype

如果我使用以下功能:

clusters.prototype.shop_iqns_selected_class = function() {
    if(this.viewport_width < 980) {
        $(this.iqns_class).each(function() {
            $(this.iqn).on('click', function() {
                if($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                } else {
                    $(this).addClass('selected');
                }
            });
        });
    }
}

要向群集功能添加属性,我知道使用this.viewport_width我指的是我定义this.viewport_width的父功能,但是当我使用jQuery选择器$(this),我指的是$.on()函数的父级吗?

2 个答案:

答案 0 :(得分:2)

不要在整个代码中使用this。像$.each这样的方法可以为您提供另一个参考:

$(".foo").each(function(index, element){
  /* 'element' is better to use than 'this'
     from here on out. Don't overwrite it. */
});

此外,$.on通过事件对象提供相同的内容:

$(".foo").on("click", function(event) {
  /* 'event.target' is better to use than
     'this' from here on out. */
});

当你的嵌套运行得很深时,使用this的模糊性太大了。当然,您可以在活跃使用中找到的另一种方法是直接在回调中创建that的别名,等于this

$(".foo").on("click", function(){
  var that = this;
  /* You can now refer to `that` as you nest,
     but be sure not to write over that var. */
});

我更喜欢在参数或事件对象中使用jQuery提供的值。

答案 1 :(得分:2)

在JavaScript中,this完全由如何调用函数定义。 jQuery的each函数以一种将this设置为每个元素值的方式调用你给它的迭代器函数,因此在该迭代器函数中,this不再引用它所引用的内容。其余的代码。

使用闭包上下文中的变量很容易解决这个问题:

clusters.prototype.shop_iqns_selected_class = function() {
    var self = this; // <=== The variable
    if(this.viewport_width < 980) {
        $(this.iqns_class).each(function() {
            // Do this *once*, you don't want to call $() repeatedly
            var $elm = $(this);

            // v---- using `self` to refer to the instance
            $(self.iqn).on('click', function() {
                // v---- using $elm
                if($elm.hasClass('selected')) {
                    $elm.removeClass('selected');
                } else {
                    $elm.addClass('selected');
                }
            });
        });
    }
}

我继续使用this来引用每个DOM元素,但你可以接受迭代器函数的参数,所以没有歧义:

clusters.prototype.shop_iqns_selected_class = function() {
    var self = this; // <=== The variable
    if(this.viewport_width < 980) {
        // Accepting the args -----------v -----v
        $(this.iqns_class).each(function(index, elm) {
            // Do this *once*, you don't want to call $() repeatedly
            var $elm = $(elm);

            // v---- using `self` to refer to the instance
            $(self.iqn).on('click', function() {
                // v---- using $elm
                if($elm.hasClass('selected')) {
                    $elm.removeClass('selected');
                } else {
                    $elm.addClass('selected');
                }
            });
        });
    }
}

更多阅读(我的博客中关于JavaScript中this的帖子)

相关问题