简体   繁体   English

.on单击以创建动态创建的项目

[英].on Click for a dynamically created item

I am appending a <li> and when I try to click it using the new .on event, it doesn't work. 我附加了<li> ,当我尝试使用新的.on事件单击它时,它不起作用。 I don't want to use the .live event since it might be going to be deprecated in the future. 我不想使用.live事件,因为它将来可能会被弃用。

Here is my example: http://jsfiddle.net/2Lbbe/ 这是我的示例: http : //jsfiddle.net/2Lbbe/

This works for the first item, if you create a new the alert doesn't work. 这适用于第一个项目,如果您创建一个新警报将不起作用。

Anyone know how can I solve this problem without using live? 有人知道我不使用直播怎么解决这个问题?

You are essentially trying to do what used to be called .delegate(). 您实际上是在尝试做过去称为.delegate()的事情。 Attach the event handler to something permanent, then look inside for your targets. 将事件处理程序附加到永久性对象,然后在内部寻找目标。

$("#bxs").on('click', 'li',function() {

your updated fiddle 您更新的小提琴

From the docs : 文档

.on( events [, selector] [, data] , handler ) .on(事件[,选择器] [,数据],处理程序)

Description: Attach an event handler function for one or more events to the selected elements. 说明: 将一个或多个事件的事件处理程序功能附加到所选元素。

.on() is now capable of serving the purpose of .bind() .live() and .delegate() depending on how it is used. .on()现在能够根据其使用方式来实现.bind().live()和.delegate()的目的。 If you want a handler to apply to future items you have to make the final selection using the optional [,selector] 如果要使处理程序应用于将来的项目,则必须使用可选的[,selector]进行最终选择

You're quite close, all you need to do is change your selector setup: 您已经很接近了,您需要做的就是更改选择器设置:

From

$("#bxs li").on('click',function() {

To

$("#bxs").on('click', 'li',function() {

Here's an update to your jsfiddle: http://jsfiddle.net/jasper/2Lbbe/2/ 这是对jsfiddle的更新: http : //jsfiddle.net/jasper/2Lbbe/2/

Using the .on() function like this is the same as the old .delegate() function: 像这样使用.on()函数与旧的.delegate()函数相同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM