如果id不存在,为什么$('#id')返回true? [英] Why does $('#id') return true if id doesn't exist?

查看:151
本文介绍了如果id不存在,为什么$('#id')返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是想知道为什么jQuery返回true如果我试图通过id结构选择器找不到DOM结构中不存在的元素。

I always wondered why jQuery returns true if I'm trying to find elements by id selector that doesnt exist in the DOM structure.

像这样:

<div id="one">one</div>

<script>
    console.log( !!$('#one') ) // prints true
    console.log( !!$('#two') ) // is also true! (empty jQuery object)
    console.log( !!document.getElementById('two') ) // prints false
</script>

我知道我可以使用 !! $('#two')。长度因为长度=== 0如果对象是空的,但我认为选择器会在找到时返回该元素,否则 null (比如原生 document.getElementById 确实如此。)

I know I can use !!$('#two').length since length === 0 if the object is empty, but it seems logical to me that a selector would return the element if found, otherwise null (like the native document.getElementById does).

F.ex,这个逻辑无法完成在jQuery中:

F.ex, this logic can't be done in jQuery:

var div = $('#two') || $('<div id="two"></div>');

如果未找到ID选择器返回null,那么更合乎逻辑吗?

Wouldnt it be more logical if the ID selector returned null if not found?

任何人?

推荐答案

选择此行为是因为否则jQuery会定期抛出NullReference例外

几乎所有jQuery函数都返回一个jQuery对象作为有问题的Dom元素的包装器,因此你可以使用点表示法。

Almost all jQuery functions return a jQuery object as a wrapper around the Dom elements in question, so you can use dot notation.

$("#balloon").css({"color":"red"});

现在想象一下 $(#balloon)返回 null 。这意味着 $(#balloon)。css({color:red});
会抛出错误,而不是默默地做没有你想象的那样。

Now imagine $("#balloon") returned null. That means that $("#balloon").css({"color":"red"}); would throw an error, rather than silently doing nothing as you would expect.

因此,你只需要使用 .length 。 size()

Hence, you just gotta use .length or .size().

这篇关于如果id不存在,为什么$('#id')返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆