admin管理员组

文章数量:1321997

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

And

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

The alert gives and undefined output, just 'undefined'. I have a list of customers and a click on #showKey should reveal the key for the clicked customer.

Whats wrong with my code?

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

And

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

The alert gives and undefined output, just 'undefined'. I have a list of customers and a click on #showKey should reveal the key for the clicked customer.

Whats wrong with my code?

Share Improve this question asked May 10, 2012 at 20:08 DarkLeafyGreenDarkLeafyGreen 70.5k136 gold badges391 silver badges616 bronze badges 1
  • Why do you use each on id selector? do you have multiple elements with the same id? It's an invalid HTML! – gdoron Commented May 10, 2012 at 20:21
Add a ment  | 

4 Answers 4

Reset to default 6

You cannot have multiple elements with the same ID - use a class instead. Additionally, you don't need the call to .each -- use a class selector instead:

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

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

you can use data attribute:

<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/LKArX/

You do not need the jQuery each function.

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

The problem with your code is in your usage of

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

You should simply use

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

to bind the click event to every showkey id'd element.

本文标签: javascriptjQuery check click for each linkStack Overflow