jquery 1.7追加不工作后点击事件

时间:2013-12-17 17:18:29

标签: javascript jquery events onclick

我正在玩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时,控制台上没有输出?为什么事件处理不起作用?

2 个答案:

答案 0 :(得分:8)

您必须绑定到最近的静态父级 这个案例test-container

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

答案 1 :(得分:2)

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

您的代码应如下所示(而不是$(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>" );
});