使用jQuery奇怪行为向下拉列表添加选项

时间:2014-06-12 15:42:51

标签: javascript jquery html

我有两个下拉列表,可以使用jQuery获取它们的选项。在大多数情况下,他们工作得很好。我遇到的唯一问题是,当我尝试添加一个“全部”选项时,只需要一个。

$("#dropdown").prepend($('<option>', {value: '',text: 'Select Fiscal Year'})).attr("selected","selected").append($('<option>', {value: 'All',text: 'All'}));
$("#dropdownRO").prepend($('<option>', {value: '',text: 'Select RO'})).attr("selected","selected").append($('<option>', {value: 'All',text: 'All'}));

你可以看到两者几乎完全相同,但只有一个同时采用“.append($('',{value:'All',text:'All'}))”。如果我从一个删除,那么另一个添加选项。我甚至尝试过:

 $("#dropdown").prepend($('<option>', {value: 'All',text: 'All'}));
 $("#dropdownRO").prepend($('<option>', {value: 'All',text: 'All'}));

同样的事情发生了。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我意识到问题是我在错误的地方运行它。这种方式可行:

$().SPServices({
operation: "GetListItems",
async: false,
listName: "{ListID}",
CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>",
completefunc: function (xData, Status) {
    $(xData.responseXML).SPFilterNode("z:row").each(function () {
        var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
        var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
        $("#dropdown").append(dropDown);
        $("#dropdownRO").append(dropDownRO);
    }); //end of each() function
    /////////////Deletes duplicates from dropdown list////////////////
    var usedNames = {};
    $("#dropdown > option, #dropdownRO > option").each(function () {
        if (usedNames[this.text]) {
            $(this).remove();
        } else {
            usedNames[this.text] = this.value;
        }
    });
    //Adds All and Select Options--------------
    $("#dropdown").append($('<option>', {
        value: 'All',
        text: 'All'
    })).prepend($('<option>', {
        value: '',
        text: 'Select Fiscal Year',
        select: 'selected'
    }));
    $("#dropdownRO").prepend($('<option>', {
        value: '',
        text: 'Select RO'
    })).attr("selected", "selected").append($('<option>', {
        value: 'All',
        text: 'All'
    }));
} //end of completeFunc
}); //end of SPServices