gpt4 book ai didi

javascript - .click() 不适用于特定索引

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:03 25 4
gpt4 key购买 nike

我正在创建一个动态菜单,我可以在其中添加和删除新表单。

<input type="button" value="generate form" id="test"/>
<div id="form1"></div>

<script>
$(document).ready(function() {
$("#test").click(function() {
$("#form1").append("<select id='score-attempt'><option value='penalty'>penalty</option></select><input type='button' value='remove' id='remove'/><br>");
});

$("#form1 #remove").click(function() {
alert($(this).index());
});
});

问题是点击删除永远不会触发警告框。

谢谢

最佳答案

问题是该元素是后来添加的,在加载dom时不存在。因此,点击事件必须从一个已经存在的元素中委托(delegate),例如像这样:

$(document).on("click", "#remove", function(){
alert($(this).index() );
});

代替$(document),每个其他静态父元素都可以用于事件委托(delegate),就像示例一样。

评论更新:如前所述,$(document) 仅作为示例。我也更喜欢在这里使用 $("#form1") 就像 mithunsatheesh 建议的那样。

并供引用:https://api.jquery.com/on/#on-events-selector-data-handler ,“直接和委托(delegate)事件”部分:

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

更新正确的索引:您将使用例如获得正确的索引

$("#form1").on("click", ".remove", function(){    
alert($(".remove").index($(this)));
});

调整为使用 remove 作为类而不是 id 作为删除按钮。 ID 必须是唯一的,因此类是更好的解决方案。 index() 从 0 开始计数,所以第一个会得到 0。

作为工作示例:Fiddle

关于javascript - .click() 不适用于特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204406/

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