I have a problem with click event; here’s the code:
jQuery:
$(document).ready(function() {
$('.myClass').click(function() {
alert($(.myClass).attr("iditem"));
});
});
HTML:
<div class="myClass" iditem="1">
1
</div>
<div class="myClass" iditem="2">
2
</div>
Two DIV with same class, but different values for the same attribute, when I click on a DIV, alert print always “1” (it seems ignoring the declaration of second DIV). Why .attr() doesn’t take the right value for the second DIV?
Assuming you have
$('.myClass').attr("iditem"), this will always return the attribute of the first element in the set, as described in the documentation [docs] þ:So instead of selecting all elements with class
myClass(that’s what$('.myClass')does, no matter where/when it is called), you want to get a reference to the clicked element. Simply do:thisalways refers to the element the event handler was bound to.I suggest to use HTML5
data-*attributes instead of custom attributes, to have at least valid HTML5:You can then use
.data()[docs] to retrieve the value.þ: You really should read jQuery’s documentation. It provides many examples and a detailed description of how each method works. Make sure you also understand how selectors [docs] work.