【发布时间】:2017-03-06 19:33:28
【问题描述】:
如何按优先级对列表项进行排序?这是一个待办事项清单。用户可以输入一个项目,选择一个优先级,并添加到列表中。
这是我的 HTML 表单:
<input id="task" type="text"/>
<select id="priority">
<option id="Normal">Normal</option>
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="If You Can">If You Can</option>
</select>
<button onclick="amitFunction()">Add</button>
<hr/>
<table>
<tr>
<th id="result"></th>
<th id="priorit"></th>
</tr>
<table>
这是我的 JS:
function amitFunction() {
/* Define vars and values */
var lia = document.createElement("p");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var pro_array = ['Urgent','Critical','Normal'];
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
/* Check if text is less than 6 chars or more than 42 chars */
if (item.length<6) {
alert('Your text must have a least 6 chars');
} else if (item.length>42) {
alert('Your text must have less than 42 chars');
} else {
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
document.getElementById('task').value='';
}
/* Change text color base on priority */
if (pro==pro_array[0]) {
$("p:last-child").css('color','red');
}
if (pro==pro_array[1]) {
$("p:last-child").css('color','orange');
}
if (pro==pro_array[2]) {
$("p:last-child").css('color','green');
}
/* Delete text when user clicks on it */
$([lia,lib]).click(function(){
$([lia,lib]).css('color','gray');
$([lia,lib]).css("text-decoration", "line-through");
});
}
我需要的是,当用户添加一个新项目时,它会按优先级排序。
- 第一:紧急
- 秒:严重
- 第三个:正常
- 第四:如果可以的话
用户添加的每个新项目都应该这样排序。我该怎么做?
这是the complete script (JSBin) 了解我需要什么。
【问题讨论】:
-
您可以创建 4 个
divdisplay : none;并将它们按您需要的“排序”顺序放置,然后根据所选优先级将任务添加到它们...如果 div 保持其“排序”位置,则正在排序。 -
我将实现自己的排序功能并将其应用于项目集合。有关更多信息,请参阅Mozilla Developer Network's page on Array.sort。您可以假设选项是字符串,并使用 switch 语句告诉 JavaScript 顺序是什么,或者使用整数值来使用自然数(这是更好的方法)。
标签: javascript jquery css html