简体   繁体   English

追加后jquery 1.7 click事件不起作用

[英]jquery 1.7 click event after append not working

I'm playing around with event-delegation from http://learn.jquery.com/events/event-delegation/ .I have the following code: 我正在通过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>

When I click on Link2 I get no output on the console? 当我单击Link2时,控制台上没有输出? Why isn't the event-handling working? 为什么事件处理不起作用?

You have to bind to the closest static parent. 您必须绑定到最接近的静态父级。
This case test-container . 此案例test-container

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

The problem is that the second link is added dynamically and the click binding happens before the second link exists. 问题是第二个链接是动态添加的,并且单击绑定是在第二个链接存在之前发生的。 That's why it has no affect on it. 这就是为什么它对此没有影响。

Your code should look like this (instead of $(document) you can also use any static parent container as Ricardo pointed out): 您的代码应如下所示(代替$(document) ,也可以使用Ricardo指出的任何静态父容器):

$(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>" );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM