本文共 2886 字,大约阅读时间需要 9 分钟。
本文翻译自:
Possible Duplicate: 可能重复:
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? 3中哪一个是检查div是否存在的正确方法?
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? 这个问题实际上并不是“如何检查div是否存在”,而是关于哪种方法更好,如果有人可以解释,为什么它更好?
参考:
The first is the most concise, I would go with that. 第一个是最简洁的,我会去那。 The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. 前两个是相同的,但第一个只是那么短,所以你将节省字节。 The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter. 第三个是完全错误的,因为该条件将始终评估为真,因为该对象永远不会为null或为此。
As karim79 mentioned, the first is the most concise. 正如karim79所提到的,第一个是最简洁的。 However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true
in if-statements. 但是我可以说第二个更容易理解,因为一些Javascript / jQuery程序员并不明白/知道在if语句中非零/ false值被评估为true
。 And because of that, the third method is incorrect. 因此,第三种方法是不正确的。
If you are simply checking for the existence of an ID, there is no need to go into jQuery , you could simply: 如果您只是检查是否存在ID,则无需进入jQuery ,您可以简单地:
if(document.getElementById("yourid") !== null){}
getElementById
returns null
if it can't be found. 如果找不到getElementById
返回null
。
. 。
If however you plan to use the jQuery object later i'd suggest: 但是,如果您打算稍后使用jQuery对象,我建议:
$(document).ready(function() { var $myDiv = $('#DivID'); if ( $myDiv.length){ //you can now reuse $myDiv here, without having to select it again. }});
A selector always returns a jQuery object, so there shouldn't be a need to check against null
(I'd be interested if there is an edge case where you need to check for null
- but I don't think there is). 选择器总是返回一个jQuery对象,所以不需要检查null
(如果有一个需要检查null
的边缘情况,我会感兴趣 - 但我认为没有)。
If the selector doesn't find anything then length === 0
which is "falsy" (when converted to bool its false). 如果选择器没有找到任何东西,则length === 0
,这是“falsy”(当转换为bool时为false)。 So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness" 因此,如果它找到了某些东西,那么它应该是“真实的” - 所以你不需要检查> 0.只是为了它的“真实性”
转载地址:http://fglgj.baihongyu.com/