2012-05-10 6 views
1
$("#showKey").each(
    $(this).click(function(){ 
     alert($(this).attr("value")); 
    }) 
); 

そしてjQueryのリンクごとに

<a id="showKey" href="#" value="{{ customer.key }}"> 
    <span class="icons icon-key"></span> 
    Show key 
</a> 

をクリックしてご確認アラートが与え、未定義の出力、単に '未定義'。顧客のリストがあり、#showKeyをクリックすると、クリックされた顧客のキーが表示されます。

私のコードで何が間違っていますか?

+0

なぜ 'each'をidセレクタに使用しますか?あなたは同じIDを持つ複数の要素を持っていますか? **無効なHTMLです!** – gdoron

答えて

6

同じIDを持つ複数の要素を持つことはできません。代わりにクラスを使用します。また、あなたは.eachの呼び出しを必要としない - の代わりにクラスセレクタを使用します。

$(".showKey").click(function(){ 
    alert($(this).data("key")); 
); 

<a class="showKey" href="#" data-key="{{ customer.key }}">Show key</a> 
3

あなたはdata属性を使用することができます:あなたは必要ありません

<a id="showKey" href="#" data-value="{{ customer.key }}"> 
    <span class="icons icon-key"></span> 
    Show key 
</a> 


$("#showKey").click(function(){ 
    alert($(this).data("value")); 
}) 

http://jsfiddle.net/LKArX/

1

jQuery each機能。

$("#showKey").click(function(){ 
    alert($(this).attr("value")); 
}); 
0

あなたのコードの問題は、あなたは、単にすべてのshowkey id'd要素にクリックイベントをバインドする

$("#showkey").click({function(){ 
    alert($this).val()); 
    } 
}); 

を使用する必要があります

$("#showkey").each({...}); 

の使用状況です。

関連する問題