繁体   English   中英

如何在 jQuery 的 class 的每个 function 中使用“this”访问 class?

[英]How do I access the class using "this" inside an each function of the class in jQuery?

假设我有一个 class 和一个如下所示的 each 方法:

var dog {
    breed: "huskey",
     
    function printBreed(){
      $("ul li").each(function() {
            $(this).html() = dog.breed;
        });
    }
}

我使页面的每个列表项都显示为“huskey”。 但是,在每个 function 中,我不能使用$(this).html() = this.breed; . 因为,这将引用列表项“li”本身。 此外,直呼object。 是否有一种通用的方式来引用 object,如“this”。

首先,让我们参考您的代码的更正版本:

const dog = { // Use `const` instead of `var`; `=` was missing.
  breed: "Husky", // Spelling.
  printBreed(){ // `function` is invalid here, so use a method instead.
    $("ul li").each(function(){
      $(this).html(dog.breed); // Assignment to a method call is invalid; `html` accepts an argument to set the value.
    })
  }
};

调用 jQuery each的回调 function 时将this绑定到当前迭代的元素。 显然, this不能同时引用你的元素和你的dog object。

each回调接收两个 arguments:当前索引和当前迭代的元素。 为了忽略来自 jQuery 的this绑定,只需使用箭头 function 而不是function function。 this将从词法 scope 中获取。请参阅“this”关键字如何工作? 以及如何在回调中访问正确的this获取更多详细信息。

jQuery 的工作代码如下所示:

const dog = {
  breed: "Husky",
  printBreed(){
    $("ul li").each((index, element) => $(element).html(dog.breed));
  }
};

dog.printBreed();

请注意,在您的情况下不需要each循环。 您可以像这样简单地编写代码:

const dog = {
  breed: "Husky",
  printBreed(){
    $("ul li").html(this.breed);
  }
};

dog.printBreed();

更好的是:使用.text而不是.html 为纯文本设置 HTML 是多余的。

即使每个<li>breed不同, .html接受 function 回调。 但是,您知道,请酌情使用箭头函数。


当然, 你不需要 jQuery ,所以普通版本看起来像这样:

const dog = {
  breed: "Husky",
  printBreed(){
    document.querySelectorAll("ul li").forEach((element) => element.textContent = this.breed);
  }
}

dog.printBreed();

您可以存储参考:

var dog {
    breed: "huskey",
     
    function printBreed(){
      var self = this;
      $("ul li").each(function() {
            $(this).html() = self.breed;
        });
    }
}

这个问题也一直在我的脑海里,我决定做

var dog {
    breed: "huskey",
     
    function printBreed(){
        classThis  = this
      $("ul li").each(function() {
            $(this).html() = classThis.breed;
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM