Javascript 如何将选项对象选作默认值

Javascript 如何将选项对象选作默认值,javascript,json,dom,Javascript,Json,Dom,以下代码在加载页面之前触发。现在我已经成功地用值填充了select。但我不确定如何使第一个值成为选定值 $(document).on('pagebeforeshow', '#searchpage', //This function is the whole function that runs when the pagebefore event occurs function () { //This reads the universities from the api we creat

以下代码在加载页面之前触发。现在我已经成功地用值填充了select。但我不确定如何使第一个值成为选定值

$(document).on('pagebeforeshow', '#searchpage',
//This function is the whole function that runs when the pagebefore event occurs
function () {
    //This reads the universities from the api we created
    $.getJSON(AddressAccess + "Home/university/format/json",

    function (data) {
        //The data is sent back in a collection of objects. We need to extract each object and do relative operations
        for (var i = 0; i < data.length; i++) {
            var university = data[i];
            var SelectDropDown = document.getElementById("searchuniversity");
            var NewOption = new Option(university.Name, university.UniverstiyID);

            if (i == 1) {
                SelectDropDown.add(NewOption, Selected);
            } else {
                SelectDropDown.add(NewOption);
            }

        };
    });
});
现在,如果我使用SelectDropDown.addNewOption,Selected;select中只有一个选项作为选项,我只想将从我的json数据中读取的第一个选项作为select中出现的默认选项。

将selectedIndex of SelectedDropdown设置为1:

如果您真的在谈论选项列表中的第一个选项,selectedIndex应该是0。select元素的选项数组是基于零的

[编辑]根据您的评论: 可能select已经包含一个空白选项。尝试:

if (i < 1) {
  SelectDropDown.options.length = 0;
  SelectDropDown.add(NewOption);
  SelectDropDown.selectedIndex = 0;
}
只需将设置为true:

或使用以下参数:


当我使用您的代码并加载页面时,“选择”仍显示为空,但当我单击“选择”时,将显示下拉菜单,并在该下拉菜单中选择第一项。但是“选择”并不反映在下拉对话框中选择的内容。也许这是jQuery Mobile中的一个bug?我很确定设置options.length会引发错误,而不是删除节点。编辑:好的,最新的HTML标准实现了一个特殊的HTMLOptionsCollection,与通常的HTMLCollection相比,这是允许的,但我不相信这一点SelectedIndex肯定有效,它没有显示在选择框中的原因是因为jquery mobile。我必须更改以下属性:$.mobile.selectmenu.prototype.options.hidePlaceholderMenuItems=false;但老实说,我不确定如何对代码进行格式化,以便于他人阅读。非常感谢。
if (i < 1) {
  SelectDropDown.options.length = 0;
  SelectDropDown.add(NewOption);
  SelectDropDown.selectedIndex = 0;
}
var newOption = new Option(university.Name, university.UniverstiyID);
newOption.defaultSelected = true;
var newOption = new Option(university.Name, university.UniverstiyID, true, true);