使用JS中的"sort()"方法对多个名称进行排序



我有两个按钮,第一个命名为btnClient,下面是btnSort。当我输入3个名字时,我想按字母顺序排序。

我不得不使用sort()方法,但它不起作用。

在HTML 中

<body >
<h1>Exercise 13</h1>
<input type="text" id="nameClient" size="30"  />
<button id='btnClient'>Save client</button>
<input type="text" id="listSort" size="30"  />
<button id='btnSort'>List sort</button>
<script src="script.js"></script>
</body>

在JS 中

var arrayClient = new Array();
var buttonClient = document.getElementById('btnClient');
var buttonDisplay = document.getElementById('btnSort');
buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);
function addClient(){
var i = 0;
arrayClient[i] = document.getElementById('nameClient');
i = i + 1;
document.getElementById('nameClient').value = ' ';
}
function display()
{   
arrayClient.sort();
}

我的btnSort按钮有问题,即使单击按钮btnSort也没有发生任何事情。

var arrayClient = new Array();
var buttonClient = document.getElementById('btnClient');
var buttonDisplay = document.getElementById('btnSort');
buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);
function addClient(){
var i = 0;
arrayClient[i] = document.getElementById('nameClient');
i = i + 1;
document.getElementById('nameClient').value = ' ';
}
function display()
{   
arrayClient.sort();
}
<html>

<head>

<script src="Thing.js" type="text/javascript">
</script>
<link rel="stylesheet" type="text/css" href="Main.css">
</head>
<body >
<h1>Exercise 13</h1>
<input type="text" id="nameClient" size="30"  />
<button id='btnClient'>Save client</button>
<input type="text" id="listSort" size="30"  />
<button id='btnSort'>List sort</button>
<script src="script.js"></script>
</body>
</html>

单击bntClient按钮后,使用push方法将值添加到数组中,

单击排序后,您将看到这些值被排序并显示在控制台中。

你的第二次输入毫无意义。

const arrayClient = []
const buttonClient = document.getElementById('btnClient');
const buttonDisplay = document.getElementById('btnSort');
const firstInput = document.getElementById('nameClient');
buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);
function addClient() {
arrayClient.push(firstInput.value.trim());
firstInput.value = '';
}
function display() {
arrayClient.sort();
console.log(arrayClient);
}
<html>
<head>
<script src="Thing.js" type="text/javascript">
</script>
<link rel="stylesheet" type="text/css" href="Main.css">
</head>
<body>
<h1>Exercise 13</h1>
<input type="text" id="nameClient" size="30" />
<button id='btnClient'>Save client</button>
<input type="text" id="listSort" size="30" />
<button id='btnSort'>List sort</button>
<script src="script.js"></script>
</body>
</html>

最新更新