如何绑定功能单元通过Ajax加载 [英] How to bind a function to Element loaded via Ajax

查看:91
本文介绍了如何绑定功能单元通过Ajax加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对夫妇的div在我的网页与CSS类=你好 另外我使用Ajax来获取一些更多的div CSS类=你好 我有一张code被称为上的div的Click事件如下:

I have a couple of Divs in my page with CSS class="hello" Further I use Ajax to fetch a few more Divs with a CSS class="hello" I have a piece of code which is called on Click event of the Divs as follows:

$('.hello').click(function(){
  alert("Hello Clicked");
})

它正常工作与那些present从开始我的网页,但不具有的div使用Ajax加载工作的div。有什么我需要做的,以绑定这个小片code与新加载的div吗?

It works fine with the Divs that are present in my page from start but does not work with Divs loaded using Ajax. Is there something I need do in order to bind this little piece of code with the newly loaded Divs too?

推荐答案

你应该使用 。对 给处理程序绑定到已经present绑定的执行过程中,另一个元素喜欢说<身体GT; ,或文件,并将它检测到孩子的事件。但理想情况下,你应该将其绑定到加载的内容的最近的共同的父。

you should use .on to bind the handler to another element that is already present during the execution of the binding, like say the <body>, or the document and have it detect the children events. but ideally, you should bind it to the nearest common parent of the content loaded.

演示

//bind to the body a "click" handler for elements that have class names of "hello"
$('body').on('click','.hello',function(){
  alert("Hello Clicked");
})

这篇关于如何绑定功能单元通过Ajax加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆