添加为jQuery选择以根据第一个选择列表选项更改第二个选择列表

时间:2017-07-25 16:18:06

标签: javascript jquery html json

我使用“Use jQuery to change a second select list based on the first select list option”中的代码 根据第一个选择列表选项更改第二个选择列表。它工作得很好。但是,如何为这两个选择的代码分配“selected”属性。

JavaScript的:

$(document).ready(function () {
"use strict";

var selectData, $states;

function updateSelects() {
    var cities = $.map(selectData[this.value], function (city) {
        return $("<option />").text(city);
    });
    $("#city_names").empty().append(cities);
}

$.getJSON("updateSelect.json", function (data) {
    var state;
    selectData = data;
    $states = $("#us_states").on("change", updateSelects);
    for (state in selectData) {
        $("<option />").text(state).appendTo($states);
    }
    $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
"NE": [
    "Smallville",
    "Bigville"
],
"CA": [
    "Sunnyvale",
    "Druryburg",
    "Vickslake"
],
"MI": [
    "Lakeside",
    "Fireside",
    "Chatsville"
    ]
}

1 个答案:

答案 0 :(得分:0)

如果您知道要选择的确切选项值,可以尝试这样的事情:

$(document).ready(function() {
  "use strict";

  var selectData, $states;

  function updateSelects() {
    var cities = $.map(selectData[this.value], function(city) {
      var selected = "";
      if (city == "Vickslake") {
        selected = "selected";
      }
      return $("<option " + selected + "/>").text(city);
    });
    $("#city_names").empty().append(cities);
  }

  $.getJSON("https://api.myjson.com/bins/oj1bb", function(data) {
    var state;
    selectData = data;
    $states = $("#us_states").on("change", updateSelects);
    for (state in selectData) {
      var selected = "";
      if (state == "CA") {
        selected = "selected";
      }
      $("<option " + selected + "/>").text(state).appendTo($states);
    }
    $states.change();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <select id="us_states"></select>
  <select id="city_names"></select>
  <script type="text/javascript" src="updateSelect.js"></script>
</body>