javascript - 如何使用 javascript 按字母顺序对 textarea 标签进行排序并在另一个 textarea 标签中输出?
问题描述
我想知道<textarea>
标签的内容如何按字母顺序排序,然后<textarea>
使用 javascript 在另一个第二个标签中输出。
之前在 StackOverflow 上问过一些与此类似的问题,但我认为他们的任何答案都不能应用于我下面的代码。
这是我的代码:
.con {
display: flex;
margin-top: 2px;
margin-left: 20px;
}
.button {
background: #4CAF50;
border: none;
outline: none;
color: #ffffff;
padding: 14px;
height: 60px;
width: 140px;
border-radius: 0 10px;
margin-top: 0px;
font-size: 22px;
cursor: pointer;
}
.txt {
display: flex;
margin-right: 20px;
background: #ffffff;
border: 0;
outline: none;
height: 700px;
width: 45%;
border-radius: 10px;
box-shadow: 0 4px 8px 0 rgba(141, 105, 105, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
margin-top: 0px;
}
.text {
border: none;
margin-top: 18px;
margin-left: 18px;
height: 660px;
width: 630px;
outline: none;
font-size: 22px;
resize: none;
}
.asci {
background: #ffffff;
border: 0;
outline: none;
height: 700px;
width: 45%;
border-radius: 10px;
box-shadow: 0 4px 8px 0 rgba(141, 105, 105, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.ascii {
border: none;
margin-top: 20px;
margin-left: 10px;
height: 660px;
width: 640px;
outline: none;
font-size: 22px;
resize: none;
}
<html>
<head>
<title>alphabetical order machine</title>
<link rel="stylesheet" href="ascii.css">
</head>
<body>
<div class="con">
<form class="txt">
<textarea class="text" id="input" type="text" placeholder="type your text here"></textarea>
<input class="button" type='button' value="alphabetize" onclick="">
</form>
<form class="asci">
<textarea class="ascii" id="output" type="text" placeholder="your alphabetized text will appear here"></textarea>
</form>
</div>
<script src="ascii.js"></script>
</body>
</html>
有谁知道如何解决这个问题?
解决方案
首先,我将从split()
将元素的值textarea
放入数组开始:
//split the value on a space character
let wordsArr = document.querySelector('#input').value.split(' ');
然后对数组进行排序:
wordsArr.sort((a, b) => {
const word1 = a.toUpperCase();
const word2 = b.toUpperCase();
if (word1 < word2) {
return -1;
}
if (word2 > word1) {
return 1;
}
/* if neither of those if statements fire, that means the words are the
same and can stay in the same position */
return 0;
};
然后将数组元素连接回单个字符串,并将其设置为另一个 textarea 的值:
document.querySelector('#output').value = wordsArr.join(' ');
MDN 参考:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
推荐阅读
- corda - 使用网络引导程序 4.0 操作系统添加新节点时,ByteSequence 不在白名单上或注释 @CordaSerializable 问题
- java - 关于将 StAX 与无穷无尽的 xml 文件流一起使用的问题
- angular - 如何按时间对一些数据进行排序?
- java - “同步动作完全有序”是什么意思?
- kubernetes - 如何在两个 Kubernetes 集群之间建立联邦?
- android - AlertDialog 和 AlertDialog.Builder 之间有什么区别?
- botframework - 错误。机器人是远程的,但服务 URL 是 localhost。如果没有隧道软件,您将不会收到回复
- flutter - 如何在 Flutter 中隐藏特定屏幕的状态栏?
- javascript - jQuery 对滑块变化的反应
- wordpress - 为什么在我的 cron 期间没有调用 error_log?