在组合框中选择值对Javascript中的项目进行排序
有没有一种快速方法可以在组合框中选择值来对项目进行排序?是否有需要添加、编辑或删除的内容 请告诉我任何想法在组合框中选择值对Javascript中的项目进行排序,javascript,combobox,selection,Javascript,Combobox,Selection,有没有一种快速方法可以在组合框中选择值来对项目进行排序?是否有需要添加、编辑或删除的内容 请告诉我任何想法 <div id="sort-wrapper" class="sort-position"> <div id="sort-container"> Sort by: <select id="sort-item"> <option value="Alphabetical";">Alphabeti
<div id="sort-wrapper" class="sort-position">
<div id="sort-container">
Sort by: <select id="sort-item">
<option value="Alphabetical";">Alphabetical</option>
<option value="low to high">Low to High Price</option>
<option value="high to low">High to Low Price</option>
</select>
</div>
</div>
<div id="content-wrapper" class="content-position">
<div id="content-container">
<li>Corsair <label>2,000</label></li>
<li>Cooler Master <label>3,000</label></li>
<li>Antec <label>1,000</label></li>
</div>
</div>
排序方式:
我真的不知道是否有一个简单的方法可以做到这一点。我见过一些框架的例子,这些框架使这种行为看起来很简单
但是,这听起来很有趣,如果我在JS/jQuery中这样做,我会:
1.将您提供的选择框标记出来,
2.将结果存储在对象数组中,
3.更改时读取选择框中的选定值
4.按所选内容对结果进行排序
5.将其更新/附加到DOM
下面是一个工作示例:
JS:
$(文档).ready(函数(){
var arr=[],$opts=1;
arr.push({“name”:“Corsair”,“price”:“2000”});
arr.push({“名称”:“冷却器主机”,“价格”:“3000”});
arr.push({“name”:“Antec”,“price”:“1000”});
$('#排序项')。更改(函数(){
$opts=$(this).find('option:selected')[0].dataset.sort;
更新内容(arr,$opts);
});
更新内容(arr,$opts);
});
函数updateContent(arr$opts){
var$result=$(“#内容容器”);
$result.text(“”);
如果($opts==1){
arr.sort(函数(a,b){返回a.name>b.name;});
}
else if($opts==2){
arr.sort(函数(a,b){返回a.price-b.price;});
}
else if($opts==3){
arr.sort(函数(a,b){返回b.price-a.price;});
}
对于(var i=0;i'+arr[i].name+“$”+arr[i].price+'');
}
}
$(document).ready( function(){
var arr = [], $opts = 1;
arr.push({"name":"Corsair","price":"2000"});
arr.push({"name":"Cooler Master","price":"3000"});
arr.push({"name":"Antec","price":"1000"});
$('#sort-item').change(function() {
$opts = $(this).find('option:selected')[0].dataset.sort;
updateContent(arr,$opts);
});
updateContent(arr,$opts);
});
function updateContent(arr,$opts) {
var $result = $('#content-container');
$result.text("");
if ( $opts == 1 ){
arr.sort( function(a,b) { return a.name > b.name; } );
}
else if ($opts == 2) {
arr.sort( function(a,b) { return a.price - b.price; } );
}
else if ($opts == 3) {
arr.sort( function(a,b) { return b.price - a.price; } );
}
for (var i =0; i< arr.length; i++) {
$result
.append('<li>'+arr[i].name+" $"+arr[i].price+'</li>');
}
}