jquery未填充选择

jquery not populating select

本文关键字:选择 填充 jquery      更新时间:2023-09-26

我正在使用jquery和jquery mobile来简单地填充一个选择元素。这是 js:

var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
SelectDropDown.add(NewOption);
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.add(NewOption);
        SelectDropDown.selectedIndex = 0;
};

这是 HTML:

<select name="searchuniversity" id="searchuniversity" required></select>

为什么这不起作用?

使用"append"而不是"add"

var ArrayUniversisities = [ 15, 16, 17 ]; // I don't know what you had in your original array, but here's a simple example.
var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
SelectDropDown.append(NewOption); // Use append instead of add.
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.append(NewOption); // Use append instead of add.
        SelectDropDown.selectedIndex = 0;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="searchuniversity" id="searchuniversity" required></select>

添加 (http://api.jquery.com/add/) 用于选择类型的环境,例如,如果您要查找多个元素,并希望向该查找添加另一个项目。

追加 (http://api.jquery.com/append/) 会将选项元素追加到选择元素。

使用 append 而不是 add:

var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
var ArrayUniversisities = [1, 2, 3, 4];
SelectDropDown.append(NewOption);
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.append(NewOption);
        SelectDropDown.selectedIndex = 0;
};

http://jsfiddle.net/hescano/1oxa2q4a/