如何使用jQuery创建一个选项数组?

时间:2015-10-26 23:41:08

标签: javascript jquery arrays

我已使用a jQuery solution中的下一个代码块仅在选择了某些菜单选项时才显示特定的div块。我不是jQuery专家,但我认为可以优化$.viewMap块,因此当我想要添加更多内容时,无需每次重复$([])$("#price").parent('div')部分该菜单中的选项。有什么建议吗?

$.viewMap = {
   '' : $([]),
   '2' : $([]),
   '4' : $("#price").parent('div'),
   '7' : $("#price").parent('div')
};

更新

我按照@epascarello的建议更新了我的代码:

var x = $([]);
var y = $("#price").parent('div');

$.viewMap = { '' : x, '2' : x, '4' : y, '7' : y };

但我想要这样的事情:

var x = $([]);
var y = $("#price").parent('div');

$.viewMap = {'null, 2' : x, '4, 7' : y};

1 个答案:

答案 0 :(得分:0)

最后我更改了所有jQuery代码(感谢@Yasitha):

jQuery(document).ready(function($) {
    var cat = ["4", "7"]; // option values for which a specific div block is displayed
    $("#price").parent('div').hide();

    $('#category').change(function(){
        if($.inArray($('#category').val(), cat) > -1) {
            $("#price").parent('div').show(); 
        } else {
            $("#price").parent('div').hide(); 
        } 
    });
});