javascript 不推荐使用 livequery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7675526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:53:57  来源:igfitidea点击:

Is livequery deprecated

javascriptjquerylivequery

提问by sameold

I'm looking at old code. I'm seeing that for elements that get added with ajax, there's lots of livequery code. Is livequery not needed anymore with the newer versions of jquery? Does anyone know after which version exactly it's not needed?

我正在查看旧代码。我看到对于使用 ajax 添加的元素,有很多 livequery 代码。较新版本的 jquery 不再需要 livequery 了吗?有谁知道在哪个版本之后不需要它?

$("#somediv").livequery(function(){
    $(this).click(function(){

    });
});

采纳答案by user113716

livequeryis an entirely different concept from .live().

livequery是一个完全不同的概念.live()

The .live()method uses event delegationto handle events that occur anywhere on the page.

.live()方法使用事件委托来处理发生在页面任何地方的事件。

livequerywill invoke handlers when DOM changes occur (via jQuery methods).

livequery将在发生 DOM 更改时调用处理程序(通过 jQuery 方法)

For the example below, when an element with class="some_class"is added to the DOM (or the class is added to an element), the first handler will run. When removed, the second.

对于下面的例子,当一个元素class="some_class"被添加到 DOM(或者类被添加到一个元素)时,第一个处理程序将运行。取下时,第二个。

$('.some_class').livequery( function() {

       // apply a plugin to the element
    $(this).somePlugin();

}, function() {

    // clean up after the element was removed

});

There should be little actualneed for livequery, but in that rare case where you need to respond to DOM changes, and have no control over the jQuery that is causing those changes, it can be useful.

应该几乎没有实际需要livequery,但是在您需要响应 DOM 更改并且无法控制导致这些更改的 jQuery 的罕见情况下,它可能很有用。

回答by Reign.85

You have to use on()and attach the event to a parent or body. Ex :

您必须使用on()并将事件附加到父级或主体。前任 :

$('#obj').livequery('click', function() { ... });
$('#obj').livequery(function() { ... });

become

变得

$('body').on('click', '#obj', function() { ... });
$('body').on('DOMNodeInserted','#obj', function() { ... });

note that DOMNodeInserted is IE9+

注意 DOMNodeInserted 是 IE9+