在没有 jQuery 的 JavaScript 中使用 $ & $$ 代替 document.querySelector/All
2007 年,我开始因为 WordPress 而编写 JavaScript 代码。当时的 JavaScript 和现在不一样。它在不同的浏览器上表现不同,而且围绕基本功能的各种 hack 也太多了,根本无法跟上 WordPress 的更新换代。
因此,我们中的许多人决定依赖 jQuery——一个简单的 JavaScript 库,具有一种单一形式的语法,可以在所有浏览器中运行。
快进到 2019 年,作为一名全职 JavaScript 开发倡导者,我提倡现代 JavaScript。因为它太棒了。不过有时我也会怀念 jQuery 的简洁,比如只需要一个$
符号就能获取元素并对其进行操作。
现在用 JavaScript,我发现自己document.querySelector
在一个应用程序中要多次执行这个操作。好吧,猜猜怎么着,有一个简单的方法,只需将该$
符号绑定到文档的document.querySelector
。
以下是您的操作方法。
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
现在您可以使用以下内容:
// Change the background color of a class.
$('.class').style.background="#BADA55";
// Change the inner HTML of an ID.
$('#id').innerHTML="<span>Cool beans!</span>";
// Select all images on the webpage.
$$('img')
// Print the image addresses for all the images on a webpage.
$$('img').forEach(img => console.log(img.src))
好好利用你的代码,玩得开心!:)
祝你平安!✌️