【问题标题】:append a suffix to the array variable name inside $.each loop为 $.each 循环内的数组变量名称附加后缀
【发布时间】:2012-06-03 16:11:56
【问题描述】:

这是我的简单标记:

<select id="firstSelect">
 <option value="1">one</option>
 <option value="2">two</option>
 <option value="3">three</option>
</select>
<select id="secondSelect"></select>

在我的 js 中,有三个不同的数组,名称是渐进式的,如下所示:

var arrayColours1 = new Array('yellow', 'blue');
var arrayColours2 = new Array('red', 'grey');
var arrayColours3 = new Array('white', 'black');

现在我想根据第一个选择的选定选项,用数组中的一个值填充第二个选择,这样:

$('#firstSelect').change(function(){
var selectedValue = $(this).children('option:selected').val();
var elem = 'arrayColours'+ selectedValue;
$.each(elem, function (index, value) {
        $('<option/>').val(value).html(value).appendTo('#secondSelect');
    });
});

但这不起作用,因为elem 现在是一个字符串。 如何解决这个问题,将“arrayColours”与后缀连接起来,并使其成为调用数组名称的变量? 非常感谢您的关注,任何帮助将不胜感激。

【问题讨论】:

    标签: jquery arrays each


    【解决方案1】:

    这比你想象的要容易。

    var colourArray = {
       set1: ["yellow", "blue"],
       set2: ["red", "gray"],
       set3: ["white", "black"]
    };
    

    当您需要一组具体的颜色时,只需这样做:

    clourArray["set" + selectedValue]
    

    关联数组是您的理想之选!

    【讨论】:

    • 感谢@Matìas,但由于特定原因,我不能使用关联数组。我读到“window”属性,你能帮我吗?非常感谢。
    【解决方案2】:

    如果你的变量传递到一个数组中会更好。

    var arrayColours = [
      ['yellow', 'blue'],
      ['red', 'grey'],
      ['white', 'black']
    ];
    
    $('#firstSelect').change(function(){
     var selected = this.value;
     $.each(arrayColours[selected-1], function(index, value) {
        $('<option/>').val(value).html(value).appendTo('#secondSelect');
     });
    });
    

    或者,您也可以使用如下对象:

    var arrayColours = {
      one: ['yellow', 'blue'],
      two: ['red', 'grey'],
      three: ['white', 'black']
    };
    

    然后

       $('#firstSelect').change(function(){
         var selected = $('option:selected', this).text();
         $.each(arrayColours.selected, function(index, value) {
            $('<option/>').val(value).html(value).appendTo('#secondSelect');
         });
        });
    

    【讨论】:

    • 正如我在 SO 中的其他问题中所问的那样,我永远无法理解为什么 - 如果您不是 PHP 开发人员 - JavaScript 代码应该使用单引号来声明字符串文字。
    • 感谢@tecodeparadox,但由于特定原因,我不能使用关联数组。我读到“window”属性,你能帮我吗?非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2022-01-20
    • 2017-03-15
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多