gpt4 book ai didi

javascript - 如何知道在列表上下文中单击了哪个 jQuery 按钮

转载 作者:行者123 更新时间:2023-11-28 04:42:43 25 4
gpt4 key购买 nike

我在一个页面上有一个故事列表,每个故事都有几个用于不同操作的 jQuery 按钮。单击按钮时,我需要知道单击的是什么故事。

目前我将每个故事都包裹在一个 div 中格式为 story_<story_id> 的 ID然后在处理程序中向上遍历并解析出 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>

这行得通,但我想知道这种技术是否有缺点,或者是否有更好的方法。

我也想到了:

  • 为每个故事使用带有 id 的隐藏输入的表单
  • 将故事 ID 放入按钮 ID 并对其进行解析等。id="report_story_123"

有没有标准的方法来处理这个问题?

最佳答案

您也可以使用数据属性来做到这一点,可能完全不需要父 ID:

<input type="button" class="report-button" data-id="1" value="Report">

然后使用 .attr() 获取它在 click 事件上是这样的:

$(function() {
$('.report-button').button()
.click(function() {
alert($(this).attr('data-id'));
});
});

You can give it a try here

关于javascript - 如何知道在列表上下文中单击了哪个 jQuery 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com