【问题标题】:Foreach HTML Element into javascript-arrayForeach HTML 元素到 javascript-array
【发布时间】:2015-12-29 16:40:28
【问题描述】:

在我的网页上,我有 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);

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

**对不起我的英语不好,我希望它足够清楚明白......

【问题讨论】:

  • 数组名称被混淆了有什么特别的原因吗?对我来说看起来很像“一号”
  • @AndrueAnderson:或者它可能只是荷兰语的“季节”。

标签: javascript jquery loops foreach


【解决方案1】:

我建议使用 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;
        }
    });

参考资料:

【讨论】:

  • 也可以在$("form input.selected[name=seizon]") 上使用$.map() 并删除对.get() 的调用
【解决方案2】:

您应该查看 JavaScript 中变量作用域的工作原理。如果您希望变量可以在函数外部访问,那么您需要在函数外部定义它。例如:

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

这样做是为了演示变量范围的工作原理,但您应该使用 David 的答案,因为它是更好的形式。

【讨论】:

    【解决方案3】:

    您将选定的元素放在each() 方法之前。另外,我不确定嵌套数组是否是您真正想要的,但我认为这是您想要的输出(也许)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2021-11-25
      • 2016-06-07
      • 2016-01-20
      • 2022-01-09
      • 2017-04-25
      • 2012-11-15
      相关资源
      最近更新 更多