gpt4 book ai didi

javascript - 如何获取文档创建后添加的点击元素的ID?

转载 作者:行者123 更新时间:2023-12-03 00:47:17 26 4
gpt4 key购买 nike

我得到了一个被点击的li的id,如下所示:

        $("#repository-tabs li").on("click", function(e) {
alert(this.id);
});

很简单,问题是,我之后动态添加 li 元素:

        $("#add-tab").click(function() {
tabs = $("#repository-tabs li").length - 1;
append_at = tabs - 2;
$("#repository-tabs li:eq(" + append_at + ")").after('<li id="repository-tab-' + tabs + '" class="tab col s3 z-depth-5"><a class="white green-text text-darken-2 waves-effect waves-light" href="javascript:void(0);">Repositório ' + tabs + '</a></li>');
});

现在,当我单击添加的 li 元素时,不会触发任何事件。那么,如何获取 future 点击项目的ID?

最佳答案

不要将事件直接应用于选项卡元素;相反,将其应用到父级并委托(delegate)它。

on() 有第二个可选参数 selector,用于过滤触发事件的所选元素的后代。

$("#repository-tabs").on("click", "li", function() {
alert(this.id);
});

来自docs :

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers

关于javascript - 如何获取文档创建后添加的点击元素的ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53195340/

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