首页 > 解决方案 > 如何使用 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>

有谁知道如何解决这个问题?

标签: javascripthtml

解决方案


首先,我将从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


推荐阅读