jquery没有填充select

时间:2015-01-21 22:45:42

标签: javascript jquery jquery-mobile

我正在使用jquery和jquery mobile来简单地填充select元素。这是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>

为什么这不起作用?

2 个答案:

答案 0 :(得分:1)

使用append代替添加:

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/

答案 1 :(得分:1)

使用&#39;追加&#39;而不是&#39;添加&#39;

&#13;
&#13;
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;
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="searchuniversity" id="searchuniversity" required></select>
&#13;
&#13;
&#13;

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

Append(http://api.jquery.com/append/)会将option元素附加到select元素。