jQuery .live()和.on():我做错了什么?

时间:2012-11-30 16:40:38

标签: jquery

我正在尝试将click事件绑定到jQuery中的某些元素(v1.8.18)。我有两个与我的选择器匹配的元素,当我正在进行绑定时,但是还有第三个元素最终将与我的选择器匹配,但是在我注册之后的某个点上它没有被标记。事件

当我使用时:

$('.collapsible h2 > .ui-icon').bind('click', toggleCollapsibleList);

...然后它正确地绑定了提前存在的两个,但显然不是第三个。当我使用时:

$('.collapsible h2 > .ui-icon').live('click', toggleCollapsibleList);

......然后他们都没有受到约束。当我使用:

$('.collapsible h2 > .ui-icon').on('click', toggleCollapsibleList);

...然后它的行为与.bind()相同。我已经使用开发人员工具确认DOM中存在所有三个元素,并在页面加载完成后匹配选择器。有谁知道我可能做错了什么?

2 个答案:

答案 0 :(得分:3)

jQuery的.on()是在 1.7 中引入的,因此弃用了.live()。您使用.on()的方式目前不正确,如果您希望它的行为类似于.live()

您实际上想要使用.on()之类的内容:

$(document).on('click', '.collapsible h2 > .ui-icon', toggleCollapsibleList);

以下内容摘自jQuery .live() docs

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

答案 1 :(得分:0)

// These will attach an event handler for all elements which match the 
// current selector NOW
$('.collapsible h2 > .ui-icon').bind('click', toggleCollapsibleList);
// is equivalent to
$('.collapsible h2 > .ui-icon').on('click', toggleCollapsibleList);


// These will attach an event handler for all elements which match the 
// current selector NOW AND IN THE FUTURE

// not recommended
$('.collapsible h2 > .ui-icon').live('click', toggleCollapsibleList); 
// is equivalent to
// recommended
$(document).on('click', '.collapsible h2 > .ui-icon', toggleCollapsibleList); 
相关问题