querySelectorAll在库中

时间:2013-08-02 11:46:01

标签: javascript

我有这段代码:

(function (window, document, undefined) {

  var g = function (sel) {

    return {

      selector: document.querySelector(sel),

      on: function (evt, fn) {
        if (this.selector) this.selector.addEventListener(evt, fn, false);
        return this;
      }
    };
  };

  window.g = window._ = g;

})(this, document);

如何在此上下文中使用querySelectorAll代替querySelector,以便我可以选择多个元素。特别是考虑到会有多种方法,例如on。如何遍历所有元素并将它们返回到它调用的方法。

1 个答案:

答案 0 :(得分:1)

selector: document.querySelectorAll(sel),
on: function (evt, fn) {
    if (this.selector) {
        for (var i=0, len=this.selector.length; i < len; i++)
            this.selector[i].addEventListener(evt, fn, false);
    return this;
}

如果必须在许多方法中重用该循环,只需创建一个包装器,类似

selector: document.querySelectorAll(sel),
forEach: function (codeToApply) {
    for (var i=0, len=this.selector.length; i < len; i++)
            codeToApply.call(this, this.selector[i]);
},
on: function (evt, fn) {
    if (this.selector) {
        this.forEach(function (element) {
            element.addEventListener(evt, fn, false);
        }
    return this;
}