javascript 为 document.querySelectorAll 制作一个短别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13383886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a short alias for document.querySelectorAll
提问by mikemaccana
I'm going to be running document.querySelectorAll() a whole lot, and would like a shorthand alias for it.
我将大量运行 document.querySelectorAll() ,并且想要一个速记别名。
var queryAll = document.querySelectorAll
queryAll('body')
TypeError: Illegal invocation
Doesn't work. Whereas:
不起作用。然而:
document.querySelectorAll('body')
Still does. How can I make the alias work?
仍然如此。我怎样才能使别名工作?
回答by Sunday Ironfoot
This seems to work:
这似乎有效:
var queryAll = document.querySelectorAll.bind(document);
bind
returns a reference to the querySelectorAll
function, changing the context of 'this' inside the querySelectorAll method to be the document object.
bind
返回对该querySelectorAll
函数的引用,将querySelectorAll 方法中“this”的上下文更改为文档对象。
The bind function is only supported in IE9+ (and all the other browsers) - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
绑定功能仅在 IE9+(和所有其他浏览器)中受支持 - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
Update:In fact you could create shortcuts to a whole range of document methods like this:
更新:事实上,您可以创建一系列文档方法的快捷方式,如下所示:
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);
回答by zlebnik
The JavaScript interpreter throws an error because querySelectorAll()
should be invoked in document context.
JavaScript 解释器抛出错误,因为querySelectorAll()
应该在文档上下文中调用。
The same error is thrown when you are trying to call console.log()
aliased.
当您尝试调用console.log()
aliased时,会抛出相同的错误。
So you need to wrap it like this:
所以你需要像这样包装它:
function x(selector) {
return document.querySelectorAll(selector);
}
回答by aloisdg moving to codidact.com
A common answer is to use $
and $$
for querySelector
and querySelectorAll
. This alias mimics jQuery's one.
一个常见的答案是使用$
and $$
for querySelector
and querySelectorAll
。这个别名模仿了 jQuery 的别名。
Example:
例子:
$ = document.querySelector.bind(document)
$$ = document.querySelectorAll.bind(document)
$('div').style.color = 'blue'
$$('div').forEach(div => div.style.background = 'orange')
div {
margin: 2px;
}
<div>
test
</div>
<section>
<div>
hello
</div>
<div>
foo
</div>
</section>
回答by Andrew Willems
My solution covers the four following use cases:
我的解决方案涵盖以下四个用例:
- document.querySelector(...)
- document.querySelectorAll(...)
- element.querySelector(...)
- element.querySelectorAll(...)
- document.querySelector(...)
- document.querySelectorAll(...)
- element.querySelector(...)
- element.querySelectorAll(...)
The code:
代码:
let doc=document,
qsa=(s,o=doc)=>o.querySelectorAll(s),
qs=(s,o=doc)=>o.querySelector(s);
In terms of parameters, the selector s
is required, but the container element object o
is optional.
在参数方面,选择器s
是必须的,而容器元素对象o
是可选的。
Usage:
用法:
qs("div")
: Queries the whole document for the first div, returns that elementqsa("div")
: Queries the whole document for all divs, returns a nodeList of all those elementsqs("div", myContainer)
: Queries just within the myContainer element for the first div, returns that elementqsa("div", myContainer)
: Queries just within the myContainer element for all divs, returns a nodeList of all those elements
qs("div")
: 查询整个文档的第一个div,返回那个元素qsa("div")
: 查询所有 div 的整个文档,返回所有这些元素的 nodeListqs("div", myContainer)
: 仅在 myContainer 元素内查询第一个 div,返回该元素qsa("div", myContainer)
: 只在 myContainer 元素内查询所有 div,返回所有这些元素的 nodeList
To make the code slightly shorter (but not quite as efficient), the qs
code could be written as follows:
为了使代码更短(但效率不高),qs
可以将代码编写如下:
let qs=(s,o=doc)=>qsa(s,o)[0];
The code above uses ES6 features (let
, arrow functions and default parameter values). An ES5 equivalent is:
上面的代码使用 ES6 特性(let
、箭头函数和默认参数值)。ES5 等效项是:
var doc=document,
qsa=function(s,o){return(o||doc).querySelectorAll(s);},
qs=function(s,o){return(o||doc).querySelector(s);};
or the equivalent shorter but less efficient ES5 version of qs
:
或等效的更短但效率较低的 ES5 版本qs
:
var qs=function(s,o){return qsa(s,o)[0];};
Below is a working demo. To ensure it works on all browsers, it uses the ES5 version, but if you're going to use this idea, remember that the ES6 version is shorter:
下面是一个工作演示。为了确保它适用于所有浏览器,它使用 ES5 版本,但如果你打算使用这个想法,请记住 ES6 版本更短:
var doc = document;
var qs=function(s,o){return(o||doc).querySelector(s);},
qsa=function(s,o){return(o||doc).querySelectorAll(s);}
var show=function(s){doc.body.appendChild(doc.createElement("p")).innerHTML=s;}
// ____demo____ _____long equivalent______ __check return___ _expect__
// | | | | | | | |
let one = qs("div"); /* doc.querySelector ("#one") */ show(one .id ); // "one"
let oneN = qs("div",one); /* one.querySelector ("div") */ show(oneN .id ); // "oneNested"
let many = qsa("div"); /* doc.querySelectorAll("div") */ show(many .length); // 3
let manyN = qsa("div",one); /* one.querySelectorAll("div") */ show(manyN.length); // 2
<h3>Expecting "one", "oneNested", 3 and 2...</h3>
<div id="one">
<div id="oneNested"></div>
<div></div>
</div>
回答by Gabe
This would work, you need to invoke the alias using call()
or apply()
with the appropriate context.
这会起作用,您需要使用call()
或apply()
使用适当的上下文来调用别名。
func.call(context, arg1, arg2, ...)
func.apply(context, [args])
var x = document.querySelectorAll;
x.call(document, 'body');
x.apply(document, ['body']);
回答by svarog
I took @David Muller's approach and one-lined it using a lambda
我采用了@David Muller 的方法,并使用 lambda 对其进行了单行排列
let $ = (selector) => document.querySelector(selector);
let $all = (selector) => document.querySelectorAll(selector);
Example:
例子:
$('body');
// <body>...</body>
回答by David Müller
function x(expr)
{
return document.querySelectorAll(expr);
}
回答by Jens T?rnell
Here is my take on it. If the selector has multiple matches, return like querySelectorAll
. If ony one match is found return like querySelector
.
这是我的看法。如果选择器有多个匹配项,则返回 like querySelectorAll
。如果找到任何匹配项,则返回类似querySelector
.
function $(selector) {
let all = document.querySelectorAll(selector);
if(all.length == 1) return all[0];
return all;
}
let one = $('#my-single-element');
let many = $('#multiple-elements li');
2019 update
2019年更新
Today I made a new take on the problem. In this version you can also use a base like this:
今天我对这个问题有了新的看法。在这个版本中,您还可以使用这样的基础:
let base = document.querySelectorAll('ul');
$$('li'); // All li
$$('li', base); // All li within ul
Functions
职能
function $(selector, base = null) {
base = (base === null) ? document : base;
return base.querySelector(selector);
}
function $$(selector, base = null) {
base = (base === null) ? document : base;
return base.querySelectorAll(selector);
}
回答by Marek Lisiecki
function $(selector, base = null) { base = (base === null) ? document : base; return base.querySelector(selector); } function $$(selector, base = null) { base = (base === null) ? document : base; return base.querySelectorAll(selector); }
function $(selector, base = null) { base = (base === null) ? document : base; return base.querySelector(selector); } function $$(selector, base = null) { base = (base === null) ? document : base; return base.querySelectorAll(selector); }
Why not simplier ??? :
为什么不简单点???:
let $ = (selector, base = document) => {
let elements = base.querySelectorAll(selector);
return (elements.length == 1) ? elements[0] : elements;
}