on() 与 live() 在尚不存在的元素上单击功能 [英] on() vs live() click function on element that doesn't exist yet
问题描述
据我所知,click()
方法对我不起作用,因为我单击的元素在页面加载时不存在(DOM 就绪).
As far as I know, the click()
method isn't working for me because the element I'm clicking does not exist on page load (DOM ready).
我发现很多答案都建议使用 .live('click',function(){...})
.这很好用!
I've found many answers suggesting to use .live('click',function(){...})
. This works great!
然而,.live()
从 jQuery 1.7 开始贬值
However, .live()
is depreciated as of jQuery 1.7
所以,我尝试使用 .on('click',function(){...})
代替,但它不起作用(与 作用相同).click()
.
So, I've tried using .on('click',function(){...})
instead, but it doesn't not work (acts the same as .click()
.
有谁知道为什么,或者我可以做什么来使用 .on()
类似于 .live()
(有效)?
Does anyone know why, or what I can do to use .on()
similarly to .live()
(which works) ?
推荐答案
由于 on()
替换了 bind()
和 live()
>,您需要传递第三个参数以使用事件委托(换句话说,使其像旧的 live()
一样工作):
Since on()
replaces both bind()
and live()
, you need to pass a third parameter in order to make use of event delegation (in other words, to make it work like the old live()
):
$('#container').on('click', '.element', function(){ });
这篇关于on() 与 live() 在尚不存在的元素上单击功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!