簡體   English   中英

獲取forEach循環中的特定元素

[英]Get a specific element within forEach loop

我在forEach循環中有一個select元素列表,只想要索引為0的第一個元素。

這個元素將有一個不同的方法,我試圖阻止重復的代碼,我不想為這個單個元素創建另一個方法,我試圖找出它,但似乎我沒有成功。

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element) {
  element.addEventListener('focus', function () {
      element.style.backgroundColor = "white";
  });
  element.addEventListener('blur', function () {
      element.style.backgroundColor = "#F0F0E7";
  });

  element.addEventListener('change', function () { // I would want to get the first element here 
    // 
  });
});

您可以訪問index作為forEach方法的第二個參數,如下所示

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element, index) {
 ...

  element.addEventListener('change', function () { 
    // I would want to get the first element here 
    if (index === 0) {
      console.log('hi')
    }
  });
});

forEach具有以下語法

nodeList.forEach(callback(currentValue [, index [, array]])[, thisArg]);

所以你可以使用

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element,index,array) {
  element.addEventListener('focus', function () {
      element.style.backgroundColor = "white";
  });
  element.addEventListener('blur', function () {
      element.style.backgroundColor = "#F0F0E7";
  });

  element.addEventListener('change', function () { 
      console.log(array[0])
  });
});

暫無
暫無

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

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