为什么jQuery不能捕捉div?

我使用Ajax获得动态内容,并将其放入div中,但问题是,对于某些子div,我有不同的ID(与动态内容不同)。因此,我为这些div添加了选择器,但正如我所说的,它们是动态加载的,这意味着在加载(从另一个文件)并插入到div之前,它们在任何地方都是不可见的。当我插入动态内容时,问题就出现了。jQuery无法选择这些div:(对于我的问题有任何可能的解决方案吗?

嗯,也许我的解释不太好,所以我将用代码来说明,这是空的div:

<div id="div"></div>

以下是jQuery代码:

$(document).ready(function(){
$.get("file.php", function(data){
$("#div").html(data);


$("#somediiv").click(function(){
alert("Yeah");
});

$("#somediv").click(function(){
$.get("otherfile.php", function(data){
$("#div").html(data);
});
});

$("#somediv2").click(function(){
$.get("file.php", function(data){
$("#div").html(data);
});
});

});
});

一旦出现新的内容就会停止运作。在新的内容中,当加载“file.php”时,有一个id为“omediiv”的div,当我单击它时,将加载“therfile.php”,而在这个div的内容中,有另一个div带有id“omediiv”,但是jQuery无法捕获单击:(

I think you have to use live(). Or attach the event in the callback of $.get().

You want each dynamically loaded div to also contain the click functionality of the original div? powtac is right, live events will help you. Something like:

$(".someDivClass").live("click",function(){
  $.get("yourFile",function(data){
    $(this).append(data);
  });
});

That's assuming you want to append the data to the div you clicked, that wasn't really specified. Also you have to make sure the returned data contains the div with class "someDivClass".

Live events register for any matching selector plus all future matches (say that were added dynamically)