javascript - 如何使用 jquery 将事件附加到新添加的 anchor

标签 javascript jquery

我尝试在 #foo anchor 标记之后为新添加的 anchor 标记 (.he) 附加单击事件。但点击事件没有发生。我用过(.on)。你们能帮我吗?*

        <!DOCTYPE html>
        <html>
        <head>
        <title>Attaching event</title>
       <style>p { background:yellow; margin:6px 0; }</style>
       <script src="js/jquery.js"></script>
        </head>
    <body>
    <p>Hello</p>
    how are
    <p>you?</p>

    <button>Call remove() on paragraphs</button>

    <a id="foo" href="#" style="display:block">Testing the bind and unbind</a>


    <script>
        $("button").on('click',function () {

            $("#foo").after("<a class='he' href='#'>asdfasdf</a>");

        });
        $(".he").on('click', function(){
                alert("test");
        });     

    </script>
</body>

最佳答案

您必须委托(delegate)给这样的静态父元素

$(document).on('click','.he',function(){

//code here
});

关于javascript - 如何使用 jquery 将事件附加到新添加的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14975669/

相关文章:

asp.net-mvc - ASP.NET MVC 3 中 js 文件的 ajax 调用问题

jquery - 将 Select2 集成到 Angular2 应用程序中

php - 使用 AJAX 编辑数据库条目并返回编辑后的数据

c# - 从 GeckoFX C# 控件调用 C# 方法 (winforms)

JQuery resize() 窗口放大或缩小

javascript - 使用 bindToController 时,指令的范围变量在构造函数中未定义

javascript - 使用许多 <li> 延迟加载长 <ul> 的最简单方法

php - 将 JSON 数组返回给 ajax

JavaScript 箭头语法 : What does the equals sign on the right hand side mean?

JavaScript document.cookie 的信息少于 Chrome cookie 资源浏览器