javascript - Foreach HTML 元素放入 javascript-array

标签 javascript jquery loops foreach

在我的网页上,有 3 个名为“Seizoen”的选择按钮。我想知道选择了哪些并将值作为数组返回到我的网页中。

此时我有以下代码:

var seizoen_array = $.each($(form).children("input.selected[name=seizoen]"), function(index, evt) {
   if(typeof(seizoen)=="undefined") { var seizoen = []; }
   seizoen[index] = $(evt).val();                                   
});
alert(seizoen);
alert(seizoen_array);

但这不起作用,因为循环中的变量在循环后无法显示。 我搜索了很多,但找不到解决方案。有人可以帮助我吗? ;-)

** 抱歉我的英语不好,我希望它足够清楚以便理解...

最佳答案

我建议使用 jQuery:

// this selects the <input> elements, with the class-name of
// 'selected' and the name of 'seizon', from within the <form>
// and then uses the map() method to form a map:
var seizoen_array = $('form input.selected[name=seizon]').map(function () {
    // returning the value of the current element of the collection
    // over which we're iterating to the map:
    return this.value;
// using get() to convert the map to an array:
}).get();

或者,使用纯 JavaScript:

// selects the <input> elements, with the class-name of
// 'selected' and the name of 'seizoen' to form a
// collection:
var seizoenElements = document.querySelectorAll('input.selected[name=seizoen]'),

// converts the collection to an Array (using Array.from()),
// iterates over that array of elements to form a new Array
// using Array.prototype.map() to return a new Array from the
// original:
    seizoen_array = Array.from(seizoenElements).map(function(el) {

        // if there is a value and the trimmed value has a
        // non-zero length:
        if (el.value && el.value.trim().length) {

            // returns the value to the new Array if
            // the above conditions are met:
            return el.value;
        }
    });

引用文献:

关于javascript - Foreach HTML 元素放入 javascript-array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515240/

相关文章:

python - 使用 "while"语句循环程序

javascript - Bootstrap 导航对齐

jQuery 循环

javascript - Jquery 启用禁用按钮

javascript - 如何向 .apply() 方法添加回调?

javascript - 在 Datepicker 中,为什么不突出显示默认日期?

java - 这段Java语句中的 ":"是什么意思?

python - 如何循环遍历相关矩阵以仅提供高于特定阈值的相关对?和/或提高效率

javascript - 本地网络中的 mac 地址(JavaScript 或 PHP)

javascript - 如何从Google Geocoding API仅获取administrative_area_level_2?