简体   繁体   中英

How to make an array of options with jQuery?

I have used the next code block in a jQuery solution to display a specific div block only when some menu options are selected. I am not a jQuery expert, but I think that the $.viewMap block can be optimized, so there is no need to repeat each time the $([]) or $("#price").parent('div') parts when I want to add more options in that menu. Any suggestions?

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

UPDATE

I updated my code, as suggested by @epascarello:

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

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

but I would like something like this:

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

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

Finally I changed all the jQuery code (thanks to @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(); 
        } 
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM