[英]document.querySelector abstraction
I always found a pain to write let btn = document.querySelector('.btn');
我总是觉得很难
let btn = document.querySelector('.btn');
So I was playing with javascript and thought about doing writing a function for a sugar syntax, I came up with: 因此,我在玩javascript并考虑为糖语法编写函数,我想到了:
function dq(selector) {
return document.querySelector(selector);
}
let h1 = dq('h1');
h1.onclick = () => {
console.log('yey');
};
So, my question is: are there any downsides of doing that in my code? 所以,我的问题是:在我的代码中这样做有什么弊端?
What are you essentially doing is what code minifiers do, just manually - obfuscating the code a little bit. 本质上,您要做的是代码缩减器的工作,只是手动进行的-使代码有些混乱。
Your code is shorter, but harder to read. 您的代码更短,但更难阅读。 Also, it really only works for
document.querySelector
, not for example for document.body.querySelector
or any other element's querySelector
method. 此外,它实际上仅适用于
document.querySelector
,例如不适用于document.body.querySelector
或任何其他元素的querySelector
方法。
Instead, create a code snippet/template in your preferred IDE. 而是在您的首选IDE中创建代码段/模板。 Code snippets are designed to do exactly what you want: less writing.
代码段旨在完全满足您的需求:减少编写工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.