在我的网页上,有 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:
- jQuery:
关于javascript - Foreach HTML 元素放入 javascript-array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515240/