How do I select a class element based on its id in jQuery?
I have multiple dynamically generated buttons with a class name of ".button". Each of these are given an unknown ID value used to uniquely identify them. In jQuery I must select one and alert the values.
<div class="button" id="3"></div>
The ID value is dynamically generated, therefore I do not know it. I'm new to jQuery but am basically looking for something like this:开发者_开发技巧
$(".button").attr("id").val();
How do I target one button when there are many? Thanks!
EDIT: I want to select whichever one the user clicks. The button in this case is a comment button. There is one for each "post". And I will change the ID to begin with a letter, as I am not using HTML5, whops. :)
$(".button").click(function() {
alert($(this).attr("id"));
});
You can loop through all of them using
$(".button").each(function(index) {
alert("index: " + index + " id: " + $(this).attr("id"));
});
I would guess $('#id')
is sufficient.
I prefer the Mootools method: $('id')
as $
is just an alias for getElementById
精彩评论