如果id不存在,为什么$('#id')返回true?

编程入门 行业动态 更新时间:2024-10-26 06:32:25
本文介绍了如果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?

本文发布于:2023-10-27 16:12:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   id   true

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!