首页 > 解决方案 > 可以在 array.from 中返回元素 ID?

问题描述

是否可以使用 Array.from 循环遍历值,然后返回该特定元素的 ID?就像我下面的代码:

var inputfields = form.querySelectorAll('input[type=text]');
inputfields.forEach(field => field.addEventListener('input', setTextValue));
function setTextValue() {
   textValue = Array.from(inputfields).map(e => e !== '' ? e.value : null).filter(Boolean).join(", ");
   showValues();
}

我希望我的函数 setTextValue 可以循环遍历 的值,e然后返回该元素的 ID 而不是该值。

标签: javascript

解决方案


你是这个意思吗?

var inputfields = form.querySelectorAll('input[type=text]');
inputfields.forEach(field => field.addEventListener('input', setTextValue));
function setTextValue() {
   textValue = Array.from(inputfields)
    .filter(e => !!e.value) // Remove the elements without values
    .map(e => e.id) // Get the id for each element
    .join(", "); // comma separated ids

   showValues();
}

推荐阅读