2017-05-21 10 views
0

divの子はコンソールログに置き換えたい$ this.findは関数ではありません。変換されたオブジェクトからalt attrをどのように要素に変換するのですか

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>

答えて

0

あなたはこれを実行する必要があります。あなたが$this = $(this)[0];を行うと
、あなたが定義されていない見つけた上でHTML要素を取得します。 $(this)でfind()を呼び出す必要があります。 $(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); 
0

あなたはfindメソッドをしていないHTML要素を、取っている。このように、それはjQueryのメソッドです:

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

変更し、その行に:

const $this = $(this); 

そして、あなたのエラーは消えます。

関連する問題