簡體   English   中英

將 function 作為參數傳遞給另一個 function 並將其應用於傳入的元素

[英]Passing in a function as an argument to another function and apply it to the passed in element

我正在嘗試創建一些輔助函數,例如 jQuery 所做的,但在 vanilla JS 中。

這就是我所擁有的;

var $ = function(selector){
  var elements = typeof selector == 'string' ? document.querySelectorAll(selector) : selector;

  elements.each = function(){
    this.forEach(function(item, index){
      var element = _(this[index]);
      //How do I apply the passed in function to this element??
    })
  };
}

它是這樣使用的;

var x = 0;
$('.field').each(function(e){
  e.addClass('item-' + x);

  x++;
});

如何使用 function 我在上面傳入 $ object 並將其應用於傳入的元素?

圍繞這個問題提出了很多問題,但不是針對我的具體問題,我無法修改它們以適應我的情況。 任何幫助表示贊賞。

盡管epascarello發布了一種布置您想要完成的鏈接的方法,但我還想提出您當前設置事物的方式是矛盾的。

一個是您在創建的 elements 變量上定義 each() 方法,兩個是您定義 each() 方法以不使用任何參數,但是您在使用 go 時將 function 作為參數傳遞方法。 此外,您引用查詢的元素的方式有些混亂。

我認為您應該改為將代碼重組為:

const $ = function(selector){
  let elements;
  
  let bundle = {
      get(selector){
        return typeof selector == 'string' ? document.querySelectorAll(selector) : selector;
      },
      each(executor) {
        // instead of calling forEach on 'this', call it on the elements instead
        // thanks to closures, this each() method still has access to the elements that were queried
        elements.forEach(function(item, index){
            let tempEle = item;
            // you can call the passed executor function here
            executor();
        });
      }
  }

  elements = bundle.get(selector);

  return bundle;
}

因此,您可以如下調用它,在其中發送執行程序 function 以通過 each() 中定義的 forEach() 循環在每次迭代中應用

$('.field').each(() => {
    console.log("Calling in the each() method");
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM