2010-01-25 88 views
0

是否有可能JavaScript不适用于通过ajax请求创建的元素? 实际上,我有一个像父母和孩子一样的元素树与更多级别的部门。ajax在javascript创建元素

我有索引页上的根元素上点击,我可以retrive孩子低谷这个请求:

var get_children = function() { 
pid = $(this).attr("id"); 
//var parentid = pid 
    // store value in data variable 
    var data = { par: pid }; 
    $.getJSON("/holz/children/",data, 
     function(data){ 
     //remove the box if it already exists 
     $("#parid-" + pid).remove(); 
      // Add the messages div to the container 
      $("#container").append("<div class='box' id='parid-" + pid + "'></div>"); 
      //create the id set for the box 
      boxid = "#parid-"+pid 
      //insert the elements one after each other with the id set to the elements pk 
      $.each(data, function(i,item){ 
       $(boxid).append('<p><a '+'id="'+item.pk+'"'+' class="element" href="#">'+item.fields.title +' (id = '+ item.pk+')'+'</a>'+'</p>'); 
      }); 
     } 
    ); 
    return false; 
}; 

的问题是,由于请求doenst适用于我得到的元素我不能走得更深从第一个请求。 ajax请求调用一个django视图,该视图应该(并且它在第一个元素上)并返回一个json响应,我使用它来为子项创建一个框。

我在做什么错?

THX

回答

1

我不确定我完全理解,但它听起来像你想要一个onclick事件处理程序适用于具有某个css类.element的所有domeblements。我对吗?

如果是这样,那么只是use jQuery's live() event binder语法。这将允许您将事件绑定到现在和将来与给定选择器匹配的所有dom元素。

要使用一些自己的代码为例:

$('div.box').live('click', function() { 
    alert('you clicked me!'); 
}); 

$("#container").append("<div class='box' id='parid-" + 1 + "'></div>"); 

在我们动态地添加将有我们的点击事件绑定到它,因为我们使用了jQuery API插入它div上面的例子。

+0

约定的,动态添加的元素没有连线,因为连线代码已经运行,所以您必须使用live才能确保添加的元素也已连线。 – 2010-01-25 19:40:04

+0

thx球员......这工作。 – aschmid00 2010-01-26 07:06:29

0

不,JavaScript的始终适用于在DOM每个有效的元素,无论它是从哪里来的。

我真的不能从你的代码中理解多少,但也许你的AJAX调用注入了文档中已经存在的ID元素? 在尝试解决这些元素时会造成麻烦。

+0

你没有给新到的孩子元素,他们可以听的任何onclick事件,对吗? – 2010-01-25 16:22:59

+0

您需要重新应用您用来使链接可点击的任何功能。目前,您从AJAX调用中获得的仅仅是没有任何附加操作的死链接(这是设计)。 – 2010-01-25 16:28:54