如何知道在列表上下文中点击了哪个jQuery按钮 [英] How to know which jQuery button was clicked in list context
问题描述
我有一个页面上的故事列表,每个页面有不同的动作的几个jQuery按钮。当点击按钮时,我需要知道它被点击的故事。
目前,我将每个故事都包装在一个 div
中,其格式为 story_< story_id>
,然后在处理程序中,我遍历并解析出id。
< div id =story_1class =story>
Blah blah blah
< input type =buttonclass =report-buttonvalue =Report>
< / div>
< div id =story_2class =story>
Blah blah blah
< input type =buttonclass =report-buttonvalue =Report>
< / div>
<! - 更多故事 - >
< div id =story_9class =story>
Blah blah blah
< input type =buttonclass =report-buttonvalue =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>
这可行,但我想知道这种技术是否存在缺点,或者是否有更好的方法。
我也想过:
id =report_story_123
有没有一种标准的方法来处理这个问题?
< input type =buttonclass =report-buttondata-id =1value =Report>
然后使用点击这样的事件: =nofollow noreferrer> .attr()
/ p>
$(function(){
$('。report-button')。button()
.click(function(){
alert($(this).attr('data-id'));
});
});
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>
<!-- 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'));
});
});
这篇关于如何知道在列表上下文中点击了哪个jQuery按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!