使用数组填充下拉列表

时间:2017-04-18 16:33:09

标签: javascript jquery

我正在尝试用变量中的数据填充下拉菜单。这是我到目前为止所做的,它不起作用。我究竟做错了什么?

<script>
$(function() {
    $('#dropdownMenu1').click(function() {
        var director_names = {"director_name": ["Aaron Schneider", "Aaron Seltzer", "Abel Ferrara", "Adam Goldberg", "Adam Marcus", "Adam McKay", "Adam Rapp", "Adam Rifkin", "Adam Shankman", "Adrian Lyne", "Adrienne Shelly", "Agnieszka Holland", "Agnieszka Wojtowicz-Vosloo", "Akiva Goldsman", "Akiva Schaffer", "Alan Cohn", "Alan J. Pakula", "Alan Metter", "Alan Parker", "Alan Poul", "Alan Rudolph", "Alan Shapiro", "Alan Taylor"]};

        var myDDL = document.getElementById("dropdownMenu1");
                var i;
                for (i = 0; i < director_names.director_name.length; i++) {
                    var option = document.createElement("option");
                    option.text = director_names.director_name[i].name;

                    option.value = director_names.director_name[i].address;
                    try {
                        myDDL.options.add(option);
                    }
                    catch (e) {
                        alert(e);
                    }
                }
    });
});
</script>

1 个答案:

答案 0 :(得分:2)

您至少有一个语法错误。试试:

<script>
        $( document ).ready(function() {
        var director_names = {"director_name": ["Aaron Schneider", "Aaron Seltzer", "Abel Ferrara", "Adam Goldberg", "Adam Marcus", "Adam McKay", "Adam Rapp", "Adam Rifkin", "Adam Shankman", "Adrian Lyne", "Adrienne Shelly", "Agnieszka Holland", "Agnieszka Wojtowicz-Vosloo", "Akiva Goldsman", "Akiva Schaffer", "Alan Cohn", "Alan J. Pakula", "Alan Metter", "Alan Parker", "Alan Poul", "Alan Rudolph", "Alan Shapiro", "Alan Taylor"]}

        var myDDL = document.getElementById("dropdownMenu1");

        for (i = 0; i < director_names.director_name.length; i++) {
          var option = document.createElement("option");
          option.text = director_names.director_name[i];

          option.value = director_names.director_name[i];
          try {
            myDDL.options.add(option);
          }
          catch (e) {
            alert(e);
          }
        }
      });
</script>

而且,正如G. Petriolly所说,你只有JSON中的名字,你没有地址。我使用上面的代码创建了this jsfiddle,以显示选择框是否填充了名称。