2013-12-17 46 views
1

我与事件代表团玩弄从http://learn.jquery.com/events/event-delegation/ 。我有以下代码:的jQuery 1.7 click事件后追加不工作

<!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> 

当我点击链路2我得到的控制台上无输出?为什么不是事件处理工作?

+0

从['.on'文档](http://api.jquery.com/on/):*“**事件处理程序仅与当前选定的元素绑定;它们必须存在于当你的代码调用'.on()'**。“时。* –

+0

我花了很长时间才意识到为什么它是一个问题,直到我注意到你将新的'

回答

8

你必须绑定到最近的静态父。
这种情况下test-container

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

会更好,因为“文章a”不只是“a” – epascarello

+0

@epascarello正确,只是指出他的错误;) –

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>"); 
}); 
+0

最好是在点击行中交换“#test-container”和文档。 – epascarello

+0

@epascarello我已经添加了它 – enyce12