有人可以帮助我找到错误吗?此代码无效,我也不明白为什么。我想按价格对清单进行排序。
<html>
<head>
</head>
<body>
<button type="button" onclick="LowToHigh()">Low To High</button>
<ul id="list1">
<li data-price="25" data-quality="8">Product1</li>
<li data-price="9" data-quality="9">Product2</li>
<li data-price="17" data-quality="6">Product3</li>
</ul>
<SCRIPT>
function LowToHigh()
{
$('#list1 li').sort(sort_li).appendTo('#list1');
function sort_li(a, b) {
var price1 = Number($(a).data('price'))
var price2 = Number($(b).data('price'))
if (price1 < price2) {return -1}
else {
if (price1 > price2) {return +1}
else {return 0}
}}
}
</SCRIPT>
</body>
</html>
答案 0 :(得分:0)
以这种方式尝试使用jquery
标签将<script>
添加到代码中,并从 LowToHigh 订单中查看排序是否正常。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<button type="button" onclick="LowToHigh()">Low To High</button>
<ul id="list1">
<li data-price="25" data-quality="8">Product1</li>
<li data-price="9" data-quality="9">Product2</li>
<li data-price="17" data-quality="6">Product3</li>
</ul>
<script>
function LowToHigh()
{
$('#list1 li').sort(sort_li).appendTo('#list1');
function sort_li(a, b) {
var price1 = Number($(a).data('price'))
var price2 = Number($(b).data('price'))
if (price1 < price2) {return -1}
else {
if (price1 > price2) {return +1}
else {return 0}
}}
}
</script>
</body>
</html>
答案 1 :(得分:0)
您需要在您的<head></head>
块中包含jQuery:
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>