我正在使用一个简单的alphabetizer,但问题是它没有正确排序。
$(document).ready(function() {
var txt = $(".input-text");
$(".alphabetize").on("click", function() {
txt.val(txt.val().split(" ").sort().join(" "));
});
});

<!DOCTYPE html>
<html>
<head>
<title>Alphabetizer</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<a class="alphabetize" href="javascript:void(0)">Alphabetize</a><br />
<textarea class="input-text" placeholder="Alphabetize your text here...">China
India
United States of America
Indonesia
Brazil
Pakistan
Nigeria
Bangladesh
Russia
Japan
Mexico
Philippines
Ethiopia
Vietnam
Egypt
Germany
Iran
Turkey
Democratic Republic of the Congo
France</textarea>
</body>
</html>
&#13;
答案 0 :(得分:2)
您应该按新行(\n
)分割文字。
$(document).ready(function() {
var txt = $(".input-text");
$(".alphabetize").on("click", function() {
txt.val(txt.val().split("\n").sort().join("\n"));
});
});
<!DOCTYPE html>
<html>
<head>
<title>Alphabetizer</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<a class="alphabetize" href="javascript:void(0)">Alphabetize</a><br />
<textarea class="input-text" placeholder="Alphabetize your text here...">China
India
United States of America
Indonesia
Brazil
Pakistan
Nigeria
Bangladesh
Russia
Japan
Mexico
Philippines
Ethiopia
Vietnam
Egypt
Germany
Iran
Turkey
Democratic Republic of the Congo
France</textarea>
</body>
</html>
另外。虽然您的示例没有必要(因为所有行都以大写字母开头),但您应该知道.sort()
区分大小写,因此“ AbCdEf ”将被排序为“< EM> ACEbdf ”。
要使其不区分大小写,可以将排序方法作为参数传递,其中比较字符串.toLowerCase()
:
// ...
txt.val(txt.val().split("\n").sort(caseInsensitive).join("\n"));
// ...
function caseInsensitive(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
}