1
var options = $('#mobility-table').find('select.MobilityCountry[data="'+selectionId+'"]').data('options').filter('[data="' + id + '"]');

    options.sort(function(a,b) {
        if (a.innerHTML > b.innerHTML) return 1;
        else if (a.innerHTML < b.innerHTML) return -1;
        else return 0;

上面的代码会在选择一个国家时给我所有的城市列表。我想在变量“选项”的第一个位置添加一个默认值“全部”。任何人都可以建议我如何添加这个。非常感谢任何帮助。谢谢你。

例如:选项应该有 'All,London,Scotland,Stanmore, Watford'。

4

2 回答 2

1

You can use unshift() to add an element to the beginning of the sorted array:

If you're just trying to add text to the first element, it would be like this:

options.sort(function(a,b) {
        if (a.innerHTML > b.innerHTML) return 1;
        else if (a.innerHTML < b.innerHTML) return -1;
        else return 0;
}
options.unshift("All");

If you want to add an option element to the array, it would be like this:

var item = document.createElement("option");
item.value = "all";
item.innerHTML = "All";
options.unshift(item);

It isn't clear to me whether you're also trying to change your HTML. If so, then please show what your HTML looks like so we can advise how to add that element to the DOM. It's not clear to me what HTML item is the select item.

In jQuery, you could add the option to be the first item in the drop-down like this

// you have to fill in the appropriate selector for your select object
$("#selector for select object").prepend("<option value='all'>All</option>");
于 2013-09-20T22:25:17.680 回答
0

unshift() a new <option>:

var option = document.createElement("option");
option.value = "all";
option.appendChild(document.createTextNode("All"));
options.unshift(option);

jQuery:

options.unshift($("<option>", {text: "All", value: "all"}).get(0));
于 2013-09-20T22:26:32.377 回答