jquery$(selector).ready()代码即使没有匹配的元素也会运行

jquery $(selector).ready() code running even if no element was matched

本文关键字:元素 运行 selector ready 代码 jquery      更新时间:2023-09-26

我使用此代码仅在某些页面上运行此js。

$("body#action_new").ready(function() {
    console.log($("body#action_new"));
    console.log($("body#action_new").length);
    console.log("code is running");
}

即使body#action_new不存在,代码仍在运行。

两个控制台日志打印出来:

[]
0
code is running

什么东西?

除了文档之外,您不能对任何内容调用.ready()。在任何其他情况下,您都会得到未定义的行为。

.ready()方法只能在与当前文档匹配的jQuery对象上调用,因此可以省略选择器。

http://api.jquery.com/ready/

除了在文档上,您不能调用ready,也可以尝试

$(document).ready(function(){
if($("#action_new").size()>0){
        console.log($("body#action_new"));
        console.log($("body#action_new").length);
        console.log("code is running");
    }
});

正如@Interrobang在评论中所说,.size()方法内部使用.length,因此建议使用.length来避免函数调用的额外开销,因此上面的代码看起来像

if ($("#action_new").length > 0){

可以在选择器上调用ready()。你只需要这个:https://github.com/Verba/jquery-readyselector