添加元素动态后,JQuery绑定事件 [英] JQuery bind event after adding element dynamic
问题描述
在动态添加元素后,我有一个问题,因为它没有点击事件,所以我有以下内容:
$(。myclass> li)。click(function(){
...
});
所以基本上当我点击LI元素应该会发生,它的工作。
但是,当我添加一个新的LI元素到myclass是UL元素时,这个新添加的元素不会调用此函数。
我的问题如何重新绑定或绑定这个新元素到这个函数..?
因为其他元素,当我点击他们工作,但只有新的元素't ...我想这是绑定发生在回发或有时,但在我的情况下没有回发:/
p>您需要使用 事件委派 。您必须使用委托事件方法 .on() 。 / p>
ie
$(document).on('event' 'selector',callback_function)
在你的情况下
$(document).on('click','.myclass> li',function(){
...
});
或者如果要应用于所有列表项:
$ b $ {pre>
$(。myclass)。on('click','> li',function(){
...
} );
I have an issue after adding a element dynamically it doesn't have the click event, so i have the following:
$(".myclass > li").click(function () {
...
});
so basically when i click on LI element something should happen and it works.
But when i add a new LI element to myclass which is UL element, this newly added element doesn't call this function.
My question how do i rebind or bind this newly element to this function ..?
Because the other elements when i click on them they work, but only the new element doesn't ... i suppose it is that the binding happens on postback or somethnig but in my case there is no postback :/
You need to use Event Delegation. You have to use .on() using delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
In your case
$(document).on('click', '.myclass > li', function () {
...
});
OR if you want to apply to ALL list items:
$(".myclass").on('click', '> li', function () {
...
});
这篇关于添加元素动态后,JQuery绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!