根据选择的选项选择数组

时间:2015-01-19 22:07:51

标签: arrays object select

我有一组数组,每个数组都包含一系列对象。我想根据选择的选项选择数组。

<select  id="job" name="job">
    <option value="job_1">job_1</option>
    <option value="job_2">job_2</option>
    <option value="job_3">job_3</option>
</select>

我有一个选择更改选项的功能。 我已经尝试使用if语句来选择与选项select匹配的选项,但它只保留返回第一个数组。

var selectedValue;
        $("#job").change(function() {
            selectedValue = $("#job option:selected").val();
            return selectedValue;
        }).change();

        if(selectedValue == "job_1"){

            var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"407","wage":"489","exchange":"0.98"},
{"country_id":2,"country":"Norway","local_wage":"3200","wage":"378","exchange":"9.57"},
{"country_id":3,"country":"Austria","local_wage":"290","wage":"337","exchange":"0.87"}
];

        }


        else if(selectedValue == "job_2"){


var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"874","wage":"654","exchange":"0.24"},
{"country_id":2,"country":"Norway","local_wage":"741","wage":"365","exchange":"4.77"},
{"country_id":3,"country":"Austria","local_wage":"854","wage":"634","exchange":"0.43"}
];

        } 
        else if(selectedValue == "job_3") {


var country_data = [
{"country_id":1,"country":"Luxembourg","local_wage":"854","wage":"985","exchange":"0.25"},
{"country_id":2,"country":"Norway","local_wage":"645","wage":"874","exchange":"5.55"},
{"country_id":3,"country":"Austria","local_wage":"201","wage":"256","exchange":"0.78"}
];

                }

任何建议都很棒。

2 个答案:

答案 0 :(得分:0)

目前if语句仅在页面加载时运行一次,此时唯一选择的项目是job_1。

当选择框更改事件正在运行时,您的if语句需要运行。

我根据您的代码创建了一个简短示例,其中还包括打印当前对象以显示所选数据:http://jsfiddle.net/6a1ux1ot/6/

简短预览:

$("#job").change(function () {
    selectedValue = $("#job option:selected").val();

    if (selectedValue == "job_1") {
        ...
    }
}).change();

这是一个更新的小提琴http://jsfiddle.net/u1z7c696/1/,可以按照您的意愿运作。 问题是你的小提琴并没有包含我对你的第一个问题的修复。您从未在更改事件处理程序中运行if语句,因此country_data变量永远不会更新。关于变量声明我还修复了一些其他的js错误。

答案 1 :(得分:0)

    $("#job").change(function() {

        if('#job').val()=='job_1'){
          var country_data = [ {"country_id":1,"country":"Luxembourg","local_wage":"407","wage":"489","exchange":"0.98"},
{"country_id":2,"country":"Norway","local_wage":"3200","wage":"378","exchange":"9.57"},
{"country_id":3,"country":"Austria","local_wage":"290","wage":"337","exchange":"0.87"}
];
     }

    });

如果我理解你的问题,这应该有用!!!