如何简写出 document.querySelectorAll?

本文探讨了原生DOM选择器的使用,如getElementById、getElementsByClass等,并对比了jQuery的选择器。作者指出,虽然jQuery的选择器如querySelector、querySelectorAll方便,但直接赋值给变量可能导致执行上下文错误。解决方案是使用bind来绑定正确的上下文。文章还提醒读者,在JavaScript中,querySelectorAll返回的不是数组,而是类数组对象,需要借助Array.prototype方法来操作。最后,作者反思了在Vue和React盛行的时代,依然学习和理解原生DOM的重要性。

看了一篇风趣幽默的文章,简单记录一下~

1.原生DOM选择器

  • document.getElementById
  • document.getElementsByClass
  • document.getElementsByName
  • document.getElementsByTagName

写出来我都感觉麻烦了~接下来看看jQuery的语法糖

2.jQuery封装的DOM选择器

  • document.querySelector
  • document.querySelectorAll

但是,名字太长了,就像电影里面的反派台词一样~

var $ = document.querySelectorAll

这还像个样,测试console.debug($("body"));

报错~~~,为啥呢???不要忽视 执行上下文 !!!

分析一波:querySelectorAll 所需的执行上下文必需是 document,而我们赋值到 $ 调用后上下文变成了全局 window

好说,继续~~

var $ = document.querySelectorAll.bind(document);

全都给改了

var query = document.querySelector.bind(document);
var queryAll = document.querySelectorAll.bind(document);
var fromId = document.getElementById.bind(document);
var fromClass = document.getElementsByClassName.bind(document);
var fromTag = document.getElementsByTagName.bind(document);

注意,这些方法的返回值 nodelist 并不是数组,只是类数组。不能使用数据方法 map forEach 等

how to do ? ? ?

Array.prototype.map.call(document.querySelectorAll('button'),function(element,index){
    element.onclick = function(){
    }
})

3.闲聊

Vue、 React 大行其道,平分天下,还有多少人还在坚持原生?

我不是原教义主义者,但是我们应该经常回顾一下源头吧!!!

(function() { 'use strict'; // 强化元素等待函数 function waitForElm(selector) { return new Promise(resolve => { if (document.querySelector(selector)) { return resolve(document.querySelector(selector)); } const observer = new MutationObserver(mutations => { if (document.querySelector(selector)) { resolve(document.querySelector(selector)); observer.disconnect(); } }); observer.observe(document.body, { childList: true, subtree: true }); }); } // 主填写函数 async function fillQuestionnaire() { const questions = document.querySelectorAll('[id^="divQuestion"]'); questions.forEach(question => { // 处理单选 const radios = question.querySelectorAll('input[type="radio"]'); if (radios.length > 0) { const randomIndex = Math.floor(Math.random() * radios.length); const radio = radios[randomIndex]; radio.checked = true; triggerEvent(radio, 'click'); triggerEvent(radio, 'change'); } // 处理文本 const texts = question.querySelectorAll('input[type="text"], textarea'); texts.forEach(text => { text.value = "自动填写"; triggerEvent(text, 'input'); triggerEvent(text, 'change'); }); }); console.log('问卷填写完成'); } // 事件触发函数 function triggerEvent(element, eventName) { const event = new Event(eventName, { bubbles: true, cancelable: true }); element.dispatchEvent(event); } // 启动流程 window.addEventListener('load', async () => { try { await waitForElm('[id^="divQuestion"]'); fillQuestionnaire(); } catch (err) { console.error('等待元素超时', err); } }); })(); 帮我把它压缩成一行
最新发布
11-20
class Calculator { constructor(option) { this.display = document.getElementById(option.input) this.answer = document.getElementById(option.answer) this.buttons = document.querySelectorAll(option.btn) this.buttonMap = new Map() this.lastChar = '' this.keyMappings = { Enter: '=', Backspace: '⌫', Escape: 'c', '*': '×', '/': '÷', '.': '.', '%': '%', '+': '+', '-': '-', 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9' } this.init() } init() { this.buttons.forEach((button) => { const key = button.textContent this.buttonMap.set(key, button) button.addEventListener('click', () => this.handleInput(key)) }) document.addEventListener('keydown', this.handleKeyDown.bind(this)) } handleKeyDown(e) { const key = e.key if (this.keyMappings[key]) { e.preventDefault() this.handleInput(this.keyMappings[key]) const button = this.buttonMap.get(this.keyMappings[key]) if (button) { button.classList.add('active') setTimeout(() => button.classList.remove('active'), 100) } } } isOperator(char) { return ['+', '-', '×', '÷', '.'].includes(char) } isNumber(char) { return /[0-9]/.test(char) } isDecimal(char) { return char === '.' } isPercent(char) { return char === '%' } updateLastStr() { const currentInput = this.display.value this.lastChar = currentInput.length > 0 ? currentInput[currentInput.length - 1] : '' } checkNewStr(input) { this.updateLastStr() if (this.isOperator(input) && this.isOperator(this.lastChar)) return false if (this.isPercent(this.lastChar) && this.isNumber(input)) return false if (this.isPercent(this.lastChar) && this.isDecimal(input)) return false if (this.lastChar === '' && this.isOperator(input) && input !== '-') return false return true } handleInput(value) { if (!this.checkNewStr(value)) return switch (value) { case 'c': this.display.value = '' this.answer.value = '' this.updateLastStr() break case '⌫': this.display.value = this.display.value.slice(0, -1) this.updateLastStr() break case '=': this.calculateResult() break default: this.display.value += value } } calculateResult() { try { let expression = this.display.value.replace(/×/g, '*').replace(/÷/g, '/').replace(/%/g, '*0.01') const result = new Function(`return (${expression})`)() if (result === Infinity) throw new Error() this.answer.value = parseFloat(result.toFixed(12)) } catch (error) { this.answer.value = 'Error' } } } module.exports = Calculator 根据上述代码生成plantuml的uml图绘制代码
08-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值