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] þ:
Get the value of an attribute for the first element in the set of matched elements.
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:
$(this).attr('iditem');
this always 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:
<div class="myClass" data-item="1">
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.
I assume you want to show the itemid of the item you click on? Then, this works:
$('.myClass').click(function() {
alert($(this).attr("iditem"));
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With