Select 基于选择哪个选项的数组

Select array based on which option is selected

我有一组数组,每个数组中都有一系列对象。我想根据选择的 select 选项 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>

我有一个select更改选项的功能。 我尝试使用 if 语句 select 匹配选项 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"}
];

                }

任何建议都很好。

目前 if 语句在页面加载时仅 运行s 一次,当时唯一的 selected 项目是 job_1.

当 select 框更改事件为 运行ning 时,您的 if 语句需要 运行。

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

简短预览:

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

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

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

    $("#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"}
];
     }

    });

如果我没看错你的问题,这应该行得通!!!