我在 forEach 循环中有一个选择元素列表,并且只需要索引为 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')
}
});
});
关于javascript - 在 forEach 循环中获取特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231827/