How to know which jQuery button was clicked in list context
I have a list of stories on a page and each has several jQuery buttons for different actions. When the button is clicked, I need to know what story it is was clicked for.
Currently I have each story wrapped in a div
with an id of format story_<story_id>
and then in the handler I traverse up and parse out the id.
<div id="story_1" class="story">
Blah blah blah
<input type="button" class="report-button" value="Report">
</div>
<div id="story_2" class="story">
Blah blah blah
<input type="button" class="report-button" value="Report">
</div>
<开发者_Python百科!-- more stories -->
<div id="story_9" class="story">
Blah blah blah
<input type="button" class="report-button" value="Report">
</div>
<script type="text/javascript">
$(function() {
$('.report-button')
.button()
.click(function() {
var id_str = $(this).parents(".story").attr("id");
var id = id_str.slice(6)
alert(id);
});
});
</script>
This works, but I wonder if there is a downside to this technique or if there is a better way.
I have also thought of:
- Using a form for each story with a hidden input with the id
- Putting the story id in the button id and parsing that, etc.
id="report_story_123"
Is there a standard way to handle this?
You could do it using data attributes as well, possibly removing the need for the parent IDs altogether:
<input type="button" class="report-button" data-id="1" value="Report">
Then get it using .attr()
on the click
event like this:
$(function() {
$('.report-button').button()
.click(function() {
alert($(this).attr('data-id'));
});
});
You can give it a try here
I would do it the way you currently are, but replace .parents
with .closest
.
Try something like this.
<input type="button" class="report-button" name="story_9" value="Report">
and the javascript:
var id_str = $(this).attr("name");
I don't think there's really a standard way of doing this. Your technique seems fine.
Now if you are going to submit this id to the server then probably using a form with a hidden field and a submit button is more adapted as you will no longer need to do any parsing or rely on order of DOM elements nesting to extract this id.
精彩评论