[英]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.