javascript检查DOM元素是否存在最佳实践 [英] javascript check if DOM element exists best practice

查看:55
本文介绍了javascript检查DOM元素是否存在最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在使用之前是否应该检查项目是否存在,如此?

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() + "");
}

这不会执行 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?

推荐答案

当你真正合作时DOM元素,然后是,您应该在尝试使用它之前检查它是否存在以避免JavaScript错误。但是,你使用DOM元素,你正在使用一个(可能)包含DOM元素的jQuery对象。

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 not working with DOM elements, you're working with a jQuery object that (potentially) contains DOM elements.

jQuery函数已经处理了其元素集中没有匹配项的情况,因此在尝试使用它们之前,您不需要自己检查是否存在元素。如果您尝试使用 .get()函数或 [index] 方括号表示法。

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.

除此之外, .size() 在1.8版本中不推荐使用jQuery函数,你应该使用jQuery对象的 length 属性直接检查是否有元素,所以:

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

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

这篇关于javascript检查DOM元素是否存在最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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