我想按字母顺序对数组进行排序,从选择中的选项开始。这是我的代码:
HTML
<select id="select">
<option>Apples</option>
<option>Oranges</option>
<option>Peaches</option>
<option>Pears</option>
</select>
<div id="fruits">
<ul>
<li>Apples</li>
<li>Peaches</li>
<li>Pears</li>
<li>Oranges</li>
</ul>
</div>
的Javascript
document.getElementById('select').addEventListener('click', function() {
var index;
var fruit = ["Apples", "Oranges", "Pears", "Peaches"];
var listOutput = document.getElementById('fruits');
var text = "<ul>";
fruit.sort();
for (index = 0; index < fruit.length; index++) {
text += "<li>" + fruit[index] + "</li>";
}
text += "</ul>";
listOutput.innerHTML = text;
});
我能够按字母顺序对水果进行排序,但我希望能够根据所选内容按字母顺序排序。例如,如果我在选择中选择了橘子,我希望将水果输出为:
Oranges
Peaches
Pears
Apples
我希望按字母顺序从所选选项开始循环数组,一旦所有字符串循环播放,从字母表的顶部开始并继续直到输出所有字符串
答案 0 :(得分:1)
您可以使用
var fruit = ["Apples", "Oranges", "Pears", "Peaches"];
fruit.sort(function(a, b){
return // Ur Logic
})
答案 1 :(得分:1)
有一些方法可以达到你想要的效果。让我们开始在点击功能之外定义一些变量,这样每次点击都不会重复:
var listOutput = document.getElementById('fruits'),
select = document.getElementById('select'),
opts = select.querySelectorAll('option'),
len = opts.length,
fruit = [];
// populate fruit with the values of all options
for (var i = 0; i < len; i++) fruit.push(opts[i].value);
fruit.sort(); // sort fruit alphabetically
如果您必须支持不了解现代数组方法的旧浏览器:
select.addEventListener('click', function() {
var text = '<ul>',
idx = 0,
sel = this.selectedOptions[0].value; // get the selected value
for (; idx < len; idx++) if (fruit[idx] == sel) break; // get index of selected value
for (var i = idx; i < len; i++) { // get all items from selected to end
text += '<li>' + fruit[i] + '</li>';
}
for (var i = 0; i < idx; i++) { // get all items from first to selected
text += '<li>' + fruit[i] + '</li>';
}
listOutput.innerHTML = text + '<ul';
});
而不是两个for循环来打印项目,你可以用一个:
// get all items from selected to end, then from first to selected
for (var i = idx; i < len;) {
text += '<li>' + fruit[i] + '</li>';
if (++i == len && len != idx) i = 0, len = idx;
}
Find a DEMO here。使用现代数组方法(find them here),它写得更少:
var listOutput = document.getElementById('fruits'),
select = document.getElementById('select'),
opts = select.querySelectorAll('option'),
fruit = [].map.call(opts, function(opt) {return opt.value}).sort();
select.addEventListener('click', function() {
var idx = fruit.indexOf(this.selectedOptions[0].value),
arr = fruit.slice(idx).concat(fruit.slice(0, idx));
listOutput.innerHTML = arr.reduce(function(a, b) {
return a + '<li>' + b + '</li>'
}, '<ul>') + '</ul>';
});