簡體   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