querySelector和querySelectorAll别名

0Ds*_*Ds0 1 javascript alias dom

什么是最好的不引人注目的替代方案,为querySelectorquerySelectorAll两个document和两个跨浏览器别名Element

最直接的方式可能是

window.$ = function(selector){return document.querySelector(selector)}
window.$$ = function(selector){return document.querySelectorAll(selector)}
Run Code Online (Sandbox Code Playgroud)

当然这不会允许链接,因为函数返回总是指的是 document

$('.parent-class').$$('.child-classes')
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最好的选择是

window.$ = document.querySelector.bind(document);
window.$$ = document.querySelectorAll.bind(document);
Element.prototype.$ = Element.prototype.querySelector;
Element.prototype.$$ = Element.prototype.querySelectorAll;
Run Code Online (Sandbox Code Playgroud)

这样我们就可以做以前失败的选择器了,虽然我不确定这可能带来的不良影响,是否有人有提示/解释可以提供?

有没有人有一个很好的不引人注目的替代品?

pse*_*ant 5

我还使用该bind方法创建别名.

var $ = document.querySelector.bind(document);
var $$ = document.querySelectorAll.bind(document);
Run Code Online (Sandbox Code Playgroud)

对于元素一,我使用一个函数,apply因此它的行为就像你称之为"VanillaJS"方式一样.

Element.prototype.$ = function() {
  return this.querySelector.apply(this, arguments);
};

Element.prototype.$$ = function() {
  return this.querySelectorAll.apply(this, arguments);
};
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

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

Element.prototype.$ = function() {
  return this.querySelector.apply(this, arguments);
};

Element.prototype.$$ = function() {
  return this.querySelectorAll.apply(this, arguments);
};

alert($('.foo').innerHTML);
alert('There are ' + $$('.foo').length + ' `.foo` nodes');

var parent = $('.parent');
alert(parent.$('.child').innerText);
alert('There are ' + parent.$$('.child').length + ' children');
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div class=foo>It works!</div>
  <div class=foo>It worked again!</div>
  <div class=parent>Parent
    <div class=child>Child</div>
    <div class=child>Another Child</div>
  </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

如果你想要链接,你必须创建一些更精细的东西.您可能想要查看Bliss是否支持链接的轻量级(~3kb)库,但更像是VanillaJS而不是jQuery.