jquery 1.7追加后点击事件不起作用

jquery 1.7 click event after append not working

本文关键字:事件 不起作用 追加 jquery      更新时间:2023-09-26

我正在处理来自http://learn.jquery.com/events/event-delegation/.我有以下代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="A small web app to manage todos">
        <title>TO-DO jQuery Tests</title>
    <!--src attribute in the <script> element must point to a copy of jQuery -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $( "article" ).on( "click","a", function() {
                console.log( "The ID attribute of the link is: " + $(this).attr('id'));
            });
            //The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
            $( "#test-container" ).append("<article> <a href='"#'"id='link-2'>Link 2</a> </article>" );
        });
    </script>
</head>
<body>
    <div id="test-container">
        <article>
            <a href="#" id="link-1">Link 1</a>
        </article>
    </div>
</body>

当我点击Link2时,控制台上没有输出?为什么事件处理不起作用?

您必须绑定到最近的静态父级
本例为test-container

$( "#test-container" ).on( "click","article a", function() {
    // your code
});

问题是第二个链接是动态添加的,点击绑定发生在第二个链路存在之前。这就是为什么它对它没有影响。

您的代码应该是这样的(您也可以使用Ricardo指出的任何静态父容器,而不是$(document)):

$(document).ready(function() {
    $(document ).on( "click","article a", function() {
        console.log( "The ID attribute of the link is: " + $(this).attr('id'));
    });
    //The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
    $( "#test-container" ).append("<article> <a href='"#'"id='link-2'>Link 2</a> </article>" );
});