I am adding a new answer to reflect changes in later jQuery releases.
(我正在添加一个新答案,以反映jQuery更高版本中的更改。)
The .live() method is deprecated as of jQuery 1.7.(从jQuery 1.7开始不推荐使用.live()方法。)
From http://api.jquery.com/live/
(从http://api.jquery.com/live/)
As of jQuery 1.7, the .live() method is deprecated.
(从jQuery 1.7开始,不推荐使用.live()方法。)
Use .on() to attach event handlers.(使用.on()附加事件处理程序。)
Users of older versions of jQuery should use .delegate() in preference to .live().(较旧版本的jQuery的用户应优先使用.delegate()而不是.live()。)
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
(对于jQuery 1.7+,您可以使用.on()将事件处理程序附加到父元素,然后将与'myclass'组合的选择器作为参数传递。)
See http://api.jquery.com/on/
(参见http://api.jquery.com/on/)
So instead of...
(所以代替...)
$(".myclass").click( function() {
// do something
});
You can write...
(你可以写...)
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
(这将适用于体内带有“ myclass”的所有标签,无论该标签已经存在还是以后动态添加。)
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work.
(这里使用body标签,因为该示例没有更紧密的静态周围标签,但是当.on方法调用发生时存在的任何父标签都可以使用。)
For instance a ul tag for a list which will have dynamic elements added would look like this:(例如,列表的ul标签将添加动态元素,如下所示:)
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
(只要ul标签存在,它将起作用(尚不存在li元素)。)