1

I'm attempting to run the following simple bit of code on an html snippet contained in a php file, loaded with jquery's .load() function:

$(".thumbnail").on("click", function(event){

    alert("thumbnail clicked");
});

However, I can't seem to get it to work on this portion of my page. I have other calls to elements not loaded via ajax and they work fine with the .on() function. I was under the impression that .on() would recognize ajax loaded content.

My .thumbnail elements are pictures in img tags contained within a series of divs all loaded via ajax, jquery can't seem to find any of this content. All of my code is contained within the ready function.

Is there a way to get jquery to recognize these new elements?

Thanks.

4

1 回答 1

5

您需要动态内容的委托事件处理程序:

$('#container').load('somefile.php');

$('#container').on('click', '.thumbnail', function(event){
     // do stuff
});

最接近的非动态父元素可能是您将内容加载到其中的元素,并且您需要将事件处理程序附加到该元素,基于.thumbnail类进行过滤,如上面的代码。

于 2013-05-15T17:45:53.290 回答