Vanilla JS 代码片段

2025-05-25

Vanilla JS 代码片段

在使用 VanillaJS 编写代码时,我通常会为document.querySelector和创建快捷方式document.querySelectorAll。我还喜欢将 声明D为 的快捷方式document

const D = document
const $ = D.querySelector.bind(D)
const $$ = (selector, startNode = D) => [...startNode.querySelectorAll(selector)]

Enter fullscreen mode Exit fullscreen mode

当您在 Devtools 中打开 JS 控制台时,还要知道$$$函数已经内置,又称命令行 API 。

有了美元函数,您就可以使用类似于 jQuery 的语法:

<button id="button">click me!</button>
Enter fullscreen mode Exit fullscreen mode
$('#button').onclick = () => {
  alert('You clicked me!')
}
Enter fullscreen mode Exit fullscreen mode

如果您想使用多个元素,则可以使用$$快捷方式。document.querySelectorAll

<button> button 1 </button>
<button> button 2 </button>
<button> button 3 </button>
Enter fullscreen mode Exit fullscreen mode
$$('button').map(btn => {
  btn.style.backgroundColor = 'red'
})
Enter fullscreen mode Exit fullscreen mode

当谈到事件处理时,有一个on方法会很有用:

Array.prototype.on = function(type, listener, options) {
  this.map(el => {
    if (el instanceof Element) {
      el.addEventListener(type, listener, options)
    }
  })
  return this // for chaining
}
Enter fullscreen mode Exit fullscreen mode

这样,您可以一次在多个元素上注册多个事件处理程序:

$$('button').on('click', e => {
  const btn = e.target
  alert('You clicked ' + btn.textContent)
}).on('mouseover', e => {
  const btn = e.target
  btn.style.backgroundColor = 'red'
}).on('mouseout', e => {
  const btn = e.target
  btn.style.backgroundColor = 'blue'
})

Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/learosema/snippets-for-vanilla-js-coding-19cg
PREV
为什么在身份验证方面 Cookie 比 localStorage 更可取
NEXT
2021 年 JavaScript 开发者行业路线图