用jQuery检查div是否存在\[重复\]

jquery HTML

小胖Gil

2020-03-24

Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (listed below)

$(document).ready(function() {
    if ($('#DivID').length){
        alert('Found with Length');
    }

    if ($('#DivID').length > 0 ) {
        alert('Found with Length bigger then Zero');
    }

    if ($('#DivID') != null ) {
        alert('Found with Not Null');
    }
});

Which one of the 3 is the correct way to check if the div exists?

EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?

第3418篇《用jQuery检查div是否存在\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
JimEvaDavaid 2020.03.24

首先是最简洁的,我同意。前两个相同,但是第一个短一点,因此您将节省字节数。第三个是完全错误的,因为该条件永远将为true,因为该对象永远不会为null或虚假。

Itachi 2020.03.24

正如karim79所说,第一个是最简洁的。但是我可能会争辩说第二个更容易理解,因为对于某些Javascript / jQuery程序员来说,非零/假值true在if语句中被评估是不明显的/不为人所知因此,第三种方法是不正确的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android