gpt4 book ai didi

javascript - JQuery Textarea 字母排序器

转载 作者:行者123 更新时间:2023-11-29 14:49:05 28 4
gpt4 key购买 nike

我正在开发一个简单的字母排序器,但问题是它没有正确排序。

$(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>

最佳答案

您应该用新行 (\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"将被排序为“ACEbdf”。

要使其不区分大小写,您可以将排序方法作为参数传递,其中比较字符串 .toLowerCase():

// ...
txt.val(txt.val().split("\n").sort(caseInsensitive).join("\n"));
// ...

function caseInsensitive(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
}

关于javascript - JQuery Textarea 字母排序器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792203/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com