我不能把这件事做对。
为什么 jQuery()
默认输出一个对象?有什么方法可以用 JavaScript 实现相同的结果吗?
jQuery('#configurator-material')
init [section#configurator-material.section, context: document, selector: "#configurator-material"]
document.querySelector('#configurator-material');
<section id="configurator-material" class="section" ng-controller="materialCtrl as material">…</section>
document.querySelectorAll('#configurator-material');
NodeList [section#configurator-material.section]
一般来说,我的问题是在某些时候我有这条线:
jQuery('#myid').addClass('myclass');
我正在尝试用这样的 JS 替换它:
document.querySelector('#myid').classList.add('myclass');
我觉得应该没问题,没有错误,
但是如果页面上不存在特定元素,我会在 JS 变体上得到“无法读取 null 的属性‘classList’”。
最佳答案
处理不存在的元素
jQuery 库在内部有条件地处理不存在的元素 - 静默失败没有错误。
以 $("#nonExistent")
为例,即使在 DOM 中未检索到该元素,返回值仍将是一个 jQuery 对象实例 - 所有它的构造函数可用,如 .addClass()
等
相比之下,JavaScript 的 .querySelector()返回 Element对象,但如果未找到该元素 — 返回原语 null
。
如果您尝试访问非对象的属性,JavaScript 将破坏您的代码。就像手动写null.classList
会报错:
Uncaught TypeError: Cannot read properties of null
使用 JavaScript 可选链接 .?
模拟类似的非不稳定行为的最简单方法是使用 Optional Chaining operator .?
// jQuery
$("#notExistent").addClass("red"); // No errors
// JavaScript
document.querySelector("#notExistent")?.classList.add("red"); // No errors
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
使用Babel如果您需要 IE 浏览器的支持 - 或者使用 if
语句:
// JavaScript
const EL_notExistent = document.querySelector("#notExistent");
if (EL_notExistent) EL_notExistent.classList.add("red"); // No errors
关于javascript - 如果元素不存在,如何像 jQuery() 一样静默地使 querySelector() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63022932/