简体   繁体   English

在后来添加了jQuery的DOM上使用jQuery?

[英]use jquery on DOM that has been added afterwards with jquery?

here is the case. 就是这种情况。 with jquery ajax call i have added a new link < a id="new_link > 与jquery ajax调用我添加了一个新链接<a id =“ new_link>

and i want to use jquery on that newly added link: 我想在新添加的链接上使用jQuery:

    $(document).ready(function(){

    $.post("static/js/jquery_call.php", function(data){
        $("#div_id").html(data);
    });

    $("#new_link").click(function(){

    ..... (and so on)

but it doesnt allow me because this link was added after the DOM has been generated. 但这不允许我,因为此链接是在生成DOM之后添加的。 I can manipulate all other links but not the new added one. 我可以操纵所有其他链接,但不能操纵新添加的链接。 How can i solve this? 我该如何解决?

this question is asked every other day. 每隔一天就会问这个问题。 boy, have i milked from it 男孩,我从中挤奶了吗

$("#new_link").live('click',function(){});

Your function(data) handler is invoked when the ajax request is finished (all data present). 当ajax请求完成时 (存在所有数据),将调用您的function(data)处理程序。 In the meanwhile the execution of the script continues. 同时,脚本的执行继续。 Meaning that your $("#new_link")... code most likely is executed before the data has been added to the dom. 这意味着您的$("#new_link")...代码最有可能在将数据添加到dom之前执行。
Either use a live handler or at least move your $("#new_link") code inside the function(data) { } handler. 请使用实时处理程序,或至少将$(“#new_link”)代码移至function(data){}处理程序内。

edit: example code 编辑:示例代码

$(document).ready( function(){
  $.post("static/js/jquery_call.php", function(data){
    $("#div_id").html(data).find("#new_link").click( function() {
      alert("Test");
    });
  });
});

Use the .live() function ( doc here ) to bind to existing and newly created elements: 使用.live()函数(在doc此处 )绑定到现有和新创建的元素:

$("#new_link").live("click", function(){
  // your code here
}

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

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