问题描述
我将运行document.querySelectorAll()很多,并且想要一个简写别名。
I'm going to be running document.querySelectorAll() a whole lot, and would like a shorthand alias for it.
var queryAll = document.querySelectorAll
queryAll('body')
TypeError: Illegal invocation
不起作用。鉴于:
document.querySelectorAll('body')
仍然如此。如何使别名起作用?
Still does. How can I make the alias work?
推荐答案
这似乎有效:
var queryAll = document.querySelectorAll.bind(document);
bind
返回对<$的引用c $ c> querySelectorAll 函数,将querySelectorAll方法中'this'的上下文更改为文档对象。
bind
returns a reference to the querySelectorAll
function, changing the context of 'this' inside the querySelectorAll method to be the document object.
绑定函数是仅在IE9 +(以及所有其他浏览器)中受支持 -
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
更新:实际上,您可以创建一系列文档方法的快捷方式,如下所示:
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);
这篇关于为document.querySelectorAll创建一个简短的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!