最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery $(selector).ready() code running even if no element was matched - Stack Overflow

programmeradmin3浏览0评论

I am using this code to only run this js on certain pages.

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

Even though body#action_new does not exist, the code is running.

the two console.logs print out:

[]
0
code is running

What gives?

I am using this code to only run this js on certain pages.

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

Even though body#action_new does not exist, the code is running.

the two console.logs print out:

[]
0
code is running

What gives?

Share Improve this question asked Jan 31, 2012 at 8:28 Razor StormRazor Storm 12.3k20 gold badges95 silver badges151 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

You cannot call .ready() on anything but document. You will get undefined behavior in any other case.

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

http://api.jquery./ready/

You cannot call the ready except on the document, intead you can try

$(document).ready(function(){

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

});

As stated by @Interrobang in the ments the .size() method internally uses .length so it is advised to use .length to avoid the additional overhead of a function call, so the above code would look like

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

It's possible to call ready() on a selector. You just need this: https://github./Verba/jquery-readyselector

发布评论

评论列表(0)

  1. 暂无评论