我真的需要检查jQuery是否存在一个元素吗? [英] Do I really need to check if an element exists with jQuery?

查看:80
本文介绍了我真的需要检查jQuery是否存在一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近有一个关于如何正确检查jQuery是否存在元素的问题.我从这里找到了答案:

I recently had a question about how to correctly check if an element exists with jQuery. I found the answer from here:

https://learn. jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

总结:

if ( $( "#myDiv" ).length ) {
    // Do something
}

与我一起工作的一个人说正确的检查方法应该是:

One guy I work with says the correct way to check should be:

if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
    // Do something
}

有关系吗?我的意思是从性能或延迟方面来看,它们是否表现相同?

Does it matter? I mean from a performance or latency wise, do they perform the same?

也:

$( "#myDiv" ).show();
$( "#myDiv" ).hide();
$( "#myDiv" ).val('');

在这些类型的jQuery函数中,似乎不需要if检查,因为如果#myDiv不存在,它们不会引发错误,对吗?

In these type of jQuery functions, it seems no if check is needed because they won't raise an error if #myDiv does not exist, correct?

对于它的价值,我使用的是jQuery 1.6.4.

For what it's worth, I am using jQuery 1.6.4.

推荐答案

与我一起工作的一个人说正确的检查方法应该是:

One guy I work with says the correct way to check should be:

if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
    //do something
}

至少在$( "#myDiv" ) &&部分,他错了. jQuery的$(selector) 总是返回一个对象,根据定义,该对象是真实的.因此,这一部分毫无意义,并且无缘无故地重新查询DOM.

He's wrong, at least in terms of the $( "#myDiv" ) && part. jQuery's $(selector) always returns an object, which by definition is truthy. So that part is pointless, and re-querying the DOM for no reason.

我的意思是从性能或延迟方面来看,它们是否表现相同?

I mean from a performance or latency wise, do they perform the same?

无缘无故地重新查询DOM是一种浪费,但是大多数情况下,以任何可观察的方式都无所谓,尤其是对于$("#myDiv")这样的ID选择器而言,这些选择器已被jQuery优化为对(速度非常快).因此,一方面,是的,这是浪费大量的额外工作.另一方面,如今的浏览器是如此之快,以至于您可能要炸更大的鱼.但这可能是多余的毫无意义的代码,这是更大的问题.

Re-querying the DOM for no reason is a waste, but most of the time it doesn't matter in any observable way, and especially not for ID selectors like $("#myDiv") which are optimized by jQuery into calls to getElementById (which is blazingly-fast). So on the one hand, yes, it's wasteful extra work. On the other hand, browsers are so fast these days that you probably have bigger fish to fry. But it's probably extra pointless code, which is the larger issue.

总的来说:jQuery是基于基于集合的.这意味着对没有元素的集合的操作是无操作的.例如:

To the general point: jQuery is set-based. This means that operations on sets with no elements in them are no-ops. E.g.:

$(".foo").addClass("bar");

如果DOM中没有.foo元素,则

...是无操作(不是错误).

...is a no-op (not an error) if no .foo elements are in the DOM.

因此,请检查length是否以及何时关心是否匹配元素.如果您不关心它们,并且只想对它们执行操作,如果它们在那里,则继续进行操作(有一个重要的警告事项 1 ).

So check for length if and when you care whether you matched elements. If you don't care and just want to perform operations on them if they're there, just go ahead and do the operation (with one important caveat1).

因此,基本上,存在三种情况:

So basically, there are three scenarios:

  1. 您知道元素将在那里,所以检查是毫无意义的
    =>没有检查

  1. You know the elements will be there, so the check is pointless
    => no check

您不知道元素是否在那里,但是您不在乎,只想对它们进行操作 ,如果它们在那里
=>不检查

You don't know the elements will be there, but you don't care and just want to operate on them if they're there
=> no check

您关心元素是否由于其他原因而存在
=>进行检查

You care whether the elements are there for some other reason
=> do the check


1 这是重要的警告:如果您正在调用的jQuery函数返回的不是jQuery对象,例如val()offset()position()等. ),当您在一个空集上调用它时,它通常会返回undefined(例外是text(),它会返回"" [text()在许多方面都不像其他方法;这是其中之一) ]).因此,即使天真地假设集合是空的,编写天真的假定那些事情的代码也会返回您的期望.


1 Here's the important caveat: If you're calling a jQuery function that returns something other than a jQuery object (for instance, val() or offset() or position(), etc.), when you call it on an empty set, it will typically return undefined (the exception is text(), which will return "" [text() is not like the others in several ways; this is one of them]). So writing code that naively assumes those things will return what you're expecting, even when the set is empty, will bite you.

例如:

if ($(".foo").offset().top > 20)

...如果没有.foo元素,将引发错误,因为offset()将返回undefined,而不是对象.

...will throw an error if there are no .foo elements, because offset() will return undefined, not an object.

但这很好:

$(".foo").closest(".bar").toggleClass("baz"):

...因为即使没有.fooclosest()也会返回另一个空的jQuery集,并在其上调用toggleClass()是无操作的.

...because even if there are no .foo, closest() will return another empty jQuery set, and calling toggleClass() on it is a no-op.

因此,在处理不返回jQuery对象的访问器时,如果不确定是否要处理包含至少一个元素的集合,则需要更多防御性,例如:

So when dealing with an accessor that doesn't return a jQuery object, if you don't know for sure you're dealing with a set containing at least one element, you need more defensiveness, e.g.:

var offset = $(".foo").offset();
if (offset && offset.top > 20)

同样,大多数访问器(不返回jQuery对象)都这样做,包括val()offset()position()css(),...

Again, most accessors (that don't return jQuery objects) do this, including val(), offset(), position(), css(), ...

这篇关于我真的需要检查jQuery是否存在一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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