簡體   English   中英

如何將alt屬性從轉換后的對象轉換為元素

[英]How to get alt attr from converted object into element

我想獲取div的孩子的所有信息,但控制台記錄$ this.find不是一個函數。

  const $ClickedCells = $(".board__cell--black"); function pawnMove() { const $this = $(this)[0]; const $thisPawn = $this.find("img"); console.log($thisPawn); } $ClickedCells.on("click", pawnMove); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="board__cell--black"><img src="#" alt="lorem"></div> <div class="board__cell--black"><img src="#" alt="lorem1"></div> <div class="board__cell--black"><img src="#" alt="lorem2"></div> <div class="board__cell--black"><img src="#" alt="lorem3"></div> <div class="board__cell--black"><img src="#" alt="lorem4"></div> 

您需要這樣做:
當您執行$this = $(this)[0]; ,您將獲得未定義find的HTML元素。 您需要在$(this)上調用find( $(this) $(this)表示可使用find() jQuery元素。

const $ClickedCells = $(".board__cell--black");
function pawnMove() {
   //const $this = $(this)[0];//<---Comment out this line
   const $thisPawn = $(this).find("img");
   onsole.log($thisPawn[0].alt);
}
$ClickedCells.on("click", pawnMove);

這樣,您將獲取HTML元素,該元素沒有find方法,即jQuery方法:

const $this = $(this)[0]; // returns the HTML element

將該行更改為:

const $this = $(this); 

而且您的錯誤將消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM