2017-11-26 8 views
2

タグクラス名をチェックするための非常に簡単な関数を書いています。 .attr()を使用してdivに添付しました。アラートには問題ありません。divクラス名を確認する簡単なjQuery関数

しかし、$(this).attr('class')は正しいクラス名を表示し、ちょうど

"未定義" を表示することはできません。 実際には、$(this)ともっとやることがたくさんあるので、私が最初にやめるのは本当に悪いことです。

誰にもこれがなぜ起こったのか、それを修正する方法を教えてもらえますか?

<div class="testing class1" >Something here</div> 
<div class="testing class2" >Something here</div>  
<script> 

$("div.testing").attr('onclick', 'checkClass()'); 

function checkClass(){ 
    alert($(this).attr('class')); 
    // what do something more with "$(this)" 
} 

答えて

0

$(this) = window;

はこの試してみてくださいので、あなたが関数にこれを渡すことがあります:それはちょうど$(this)を変更するために便利です、jQueryのを使用するために

$("div.testing").attr('onclick', 'checkClass(this)'); 
function checkClass(e){ 
    alert(e.className); 
    // what do something more with e, this is you clicked element 
} 
+0

を$(e)に入れる非常に簡単な方法は、この問題を解決するために、多くのありがとう。 –

0

this参照checkClass()機能ではなく、あなたがターゲットにしようとしている要素、 は以下のデモを見ているため、アラート中にあなたのコードが出力undefined、それを実装し、以下の方法を試してみてください、あなたは簡単にする方法を学ぶ必要がありますplugin

$.fn.checkClass = function() { 
 
    $(this).on('click', function() { 
 
    console.log($(this).attr('class')); 
 
    }); 
 
} 
 
$("div.testing").checkClass();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="testing class1">Something here</div> 
 
<div class="testing class2">Something here</div>

0

jQueryのは、独自のメソッドFを持っているが、または列挙のために要素からの/からのクラスの追加/削除は何もありません。したがって、ネイティブjsメソッドを使用する必要があります。

var checkClass = e => { 
 
    alert(e.target.classList) 
 
} 
 

 
$("div.testing").click(checkClass)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="testing class1" >Something here</div> 
 
<div class="testing class2" >Something here</div>

関連する問題