我想要一个有文本框的网页。文本框下方有两个按钮,表示“按字母顺序排序”和“按数字排序”。我想要它,以便无论用户在框中输入什么,它都会排序。如果用户输入数字和字母,它将取消排序,并弹出一个提示“不能是字母和数字”。单击“按字母顺序排序”按钮时,JavaScript代码将激活并按字母顺序对单词进行排序。 “按数字排序”按钮也是如此。我似乎无法得到单词/数字来排序。
HTML:
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>
JavaScript的:
function sortAbc() {
var captureText = document.getElementById('textbox');
captureText.sort();
//Help! How to make alert pop up when numbers and letters are typed?
}
function sortNumber() {
var captureNumb = document.getElementByid('textbox');
captureNumb.sort(function(a, b){return a-b});
//Same problem here! How to make alert pop up when numbers and letters are typed?
}
答案 0 :(得分:1)
这是一个complet实时样本。
.match
)sort
function sortAbc() {
var captureText = document.getElementById('textbox');
if (captureText.value.match(/(?:^| )[\d]+(?: |$)/)) {
alert("no digits");
return;
}
var words = captureText.value.split(" ");
captureText.value = words.sort().join(" ");
}
function sortNumber() {
var captureNumb = document.getElementById('textbox');
if (captureNumb.value.match(/[^\s\d]/)) {
alert("no letters");
return;
}
var numbers = captureNumb.value.split(" ");
captureNumb.value = numbers.sort(function (a, b) { return a - b }).join(" ");
}
&#13;
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>
&#13;