jQuery:如何用.on替换.live? [英] jQuery: how to replace .live with .on?

查看:192
本文介绍了jQuery:如何用.on替换.live?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
jQuery 1.7-将live()转换为on()

Possible Duplicate:
jQuery 1.7 - Turning live() into on()

根据jQuery API( http://api.jquery.com/on/)不建议使用实时"功能,建议改用开启"功能.但是当我在代码中用"on"替换"live"时,jQuery找不到以后添加的元素:

According to the jQuery API (http://api.jquery.com/on/) the function 'live' is deprecated, it is recommended to use 'on' instead. But when I replace 'live' with 'on' in my code, jQuery can't find later added elements anymore:

这有效(但已弃用):

$('li.bibeintrag').live('click', function(){
alert('myattribute =' + $(this).attr('myattribute'));
});

这是API中"on"的示例:

This is an example from the API for 'on':

$("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
});

当我将代码更改为此("live"替换为"on")后,它不再起作用(jQuery将找不到以后添加的元素(例如,带有append的元素)):

When I change my code to this ('live' replaced with 'on') it does not work anymore (jQuery will not find later added elements (e.g. with append)):

$('li.bibeintrag').on('click', function(){
alert('myattribute =' + $(this).attr('myattribute'));
});

我做错了什么?有人可以帮忙吗?

What am I doing wrong? Can someone help, please?

推荐答案

您应将事件添加到li.bibeintrag的任何父元素.

You should add event to any parent element of li.bibeintrag.

$('ul').on('click', "li.bibeintrag", function(){
    alert('myattribute =' + $(this).attr('myattribute'));
});

这篇关于jQuery:如何用.on替换.live?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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