jQuery javascript 检查 DOM 元素是否存在最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15222914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:37:32  来源:igfitidea点击:

javascript check if DOM element exists best practice

javascriptjquery

提问by ShaneKm

What is the best practice to check if a DOM element exists in javascript?

检查javascript中是否存在DOM元素的最佳实践是什么?

Should one check if an item exists prior to using it, like so?

应该在使用之前检查物品是否存在,像这样吗?

if ($("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "").size() != 0) {
  var row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");
}

wouldn't this execute packageId.removeSpecialChars().toUpperCase()twice?

这不会执行packageId.removeSpecialChars().toUpperCase()两次吗?

OR would this be better option?

或者这会是更好的选择吗?

var row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + ""); 
if (row)
{
  // do something
}

However, wouldn't it throw an exception when not found?

但是,它在找不到时不会抛出异常吗?

回答by Anthony Grist

When you're actually working with DOM elements, then yes, you should check that it exists before you attempt to work with it to avoid JavaScript errors. However, you're notworking with DOM elements, you're working with a jQuery object that (potentially) contains DOM elements.

当您实际使用 DOM 元素时,是的,您应该在尝试使用它之前检查它是否存在以避免 JavaScript 错误。但是,您不是在使用 DOM 元素,而是在使用(可能)包含 DOM 元素的 jQuery 对象。

jQuery functions already handle cases where there are no matches in its set of elements, so you don't need to explicitly check for yourself that there are elements before attempting to work with them. You'd only need to do so if you're trying to directly reference DOM elements from inside that set, using the .get()function or the [index]square bracket notation.

jQuery 函数已经处理了在其元素集中没有匹配项的情况,因此您无需在尝试使用元素之前明确地检查自己是否存在元素。仅当您尝试使用.get()函数或[index]方括号表示法直接从该集合内部引用 DOM 元素时,才需要这样做。

As an aside, the .size()jQuery function was deprecated in version 1.8, you should use the jQuery object's lengthproperty directly to check if there are elements, so:

顺便说一句,.size()jQuery 函数在 1.8 版中已弃用,您应该length直接使用 jQuery 对象的属性来检查是否有元素,因此:

var $object = $('a-selector');
if($object.length) {
    // there's at least one matching element
}

回答by Grant Thomas

General programming conventions say don't repeat yourself. So, in this case, you could at least do the finding of the thing only once and keep a variable reference:

一般编程约定说不要重复自己。因此,在这种情况下,您至少可以只查找一次并保留变量引用:

var thing = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");

Then the selection lookup doesn't happen twice, redundant method calls removed etc. This also has the benefit of allowing you to write more self-explanatory code, when you can name a variable to something meaningful, other than thing, or, eeek!, a(though it isn't necessarily so that code must be more meaningful, people stilluse names like a!)

然后选择查找不会发生两次,删除了多余的方法调用等。这也有利于您编写更多不言自明的代码,当您可以将变量命名为有意义的东西时,除了thing, or, eeek !, a(虽然这不一定是为了让代码更有意义,但人们仍然使用像a!)

if (thing != null) { }
if (thing.size() != 0) {

} 
etc.

As for calling methods multiple times, that's often unavoidable.

至于多次调用方法,这通常是不可避免的。

回答by Jai

Better to cache it:

最好缓存它:

var machId = $("#" + machineId + packageId.removeSpecialChars().toUpperCase());
if (machId.size() != 0) {
   var row = machId;
}

回答by Sergio

It does, what you need is:

确实如此,您需要的是:

var a = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");
if (a.size()) {
    var row = a;
}

回答by Alireza

You basically need to see if the DOM element is exist in your HTML, but beer in mind that jQuery doesn't throw a fatal error if the element not exist in your DOM, but would a good practice to check, it adds one more secure layer on your code, there was something called .size() that deprecated from version 1.8, so not recommended to use even you use old version of jQuery, so the best solution at the moment would be something like below code:

您基本上需要查看 DOM 元素是否存在于您的 HTML 中,但请记住,如果该元素不存在于您的 DOM 中,jQuery 不会抛出致命错误,但检查一下是一个很好的做法,它增加了一个更安全的在你的代码层,有一个叫做 .size() 的东西从 1.8 版开始被弃用,所以即使你使用旧版本的 jQuery,也不建议使用,所以目前最好的解决方案是下面的代码:

if($('.class').length) { // check if any element with this class exist, if not exist, it return 0 and can not pass the if estatement
    // do something
}