zoukankan      html  css  js  c++  java
  • document.querySelector.bind("document")

    Making a short alias for 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

    Doesn't work. Whereas:

      document.querySelectorAll('body')

    Still does. How can I make the alias work?

    Answer:

    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.

    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);


    http://stackoverflow.com/questions/13383886/making-a-short-alias-for-document-queryselectorall
    http://stackoverflow.com/questions/14251357/what-is-the-meaning-of-document-queryselector-binddocument
  • 相关阅读:
    CodeForces
    Codeforces 1523D Love-Hate(随机化算法,sos dp)
    CodeForces
    讲题泛做
    CF vp 新题乱做
    10.11 牛客
    10.6 牛客
    10.4 牛客
    10.9 模拟考试 题解报告
    9.18 校内模拟赛 题解报告
  • 原文地址:https://www.cnblogs.com/rhett-web/p/4953370.html
Copyright © 2011-2022 走看看