我在 li 标记内有一个名单列表,我想通过点击外部链接/按钮/文字(任何内容)对它们进行排序。我搜索了这种类型的例子但没有成功。
这可能吗?我在js或jquery中做得不够好。 如果这可能对我的项目非常有帮助。
jsfiddle链接: JS Fiddle
您可以添加任何内容以完成该功能。
HTML
<p>Click me to Sort</p>
<ul>
<li> Key Roles and Functions</li>
<li> Leadership Clarity</li>
<li> Margin</li>
<li> Market Differentiation</li>
<li> Market Maturity</li>
<li> Maturity</li>
<li> Mission</li>
<li> Vision</li>
<li> Objectives</li>
<li> Operational Efficiency</li>
<li> Outlet Characteristics</li>
<li> Overall Measurements</li>
<li> Overall Performance</li>
<li> Overall Systems</li>
<li> Pain Points</li>
<li> Performance</li>
<li> Positive Culture</li>
<li> Price Optimization</li>
<li> Promotion Strategy</li>
<li> Sales Model</li>
<li> Stickiness</li>
</ul>
CSS
ul{
list-style-type:none;
width:200px;
background:#bdbdbd;
}
答案 0 :(得分:2)
试试这个:
HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<p>Click me to Sort</p>
<ul>
<li>Mission</li>
<li>Vision</li>
<li>Objectives</li>
</ul>
</body>
</html>
JavaScript:
$(function() {
$('p').click(function() {
var list = $('ul');
var listitems = list.children('li').get();
listitems.sort(function(e1, e2) {
return $(e1).text().toUpperCase().localeCompare($(e2).text().toUpperCase());
})
$.each(listitems, function(idx, itm) {
list.append(itm);
});
});
});
CSS:
ul {
list-style-type: none;
width: 200px;
background: #bdbdbd;
}
更新:(回答评论) 要排序和取消排序,您应该修改JavaScript:
$(function() {
var noSortedTxts = [];
var sortedTxts = [];
var sort = true;
$('p').click(function() {
var list = $('ul');
if (noSortedTxts.length === 0) {
var listitems = list.children('li').get();
$.each(listitems, function(idx, itm) {
noSortedTxts.push($(itm).text());
});
sortedTxts = noSortedTxts.slice(0);
sortedTxts.sort(function(t1, t2) {
return t1.toUpperCase().localeCompare(t2.toUpperCase());
});
}
if (sort) {
list.empty();
$.each(sortedTxts, function(idx, txt) {
list.append('<li>' + txt + '</li>');
});
sort = false;
} else {
list.empty();
$.each(noSortedTxts, function(idx, txt) {
list.append('<li>' + txt + '</li>');
});
sort = true;
}
});
});