- 【重点:数组对象】创建网页colors.html,具体要求如下:
- 制作一个如下图所示的表单
-
- 创建一个长度为5的数组,数组名字为myColor。
-
- 当点击“设置颜色”按钮时,利用循环结构,依次弹出5个提示框,每个提示框中输入一个代表某种颜色的单词,并将每个单词的字符串存入myColor数组中,提示框如下图所示
【提示】window.prompt(“提示的问题”)用于弹出下图所示的提示框,返回用户在文本框中输入的内容
-
- 当点击“显示颜色”按钮时,将数组中的每个颜色单词显示在左列的每个文本框中,并同时弹出一个消息框,将数组中的所有颜色以符号“&”连接在一起,显示出来,如下图所示
-
- 当点击“颜色排序”按钮时,将数组中的颜色单词按照降序顺序排序,并将排序好的颜色依次显示在右边一列的文本框中,如下图所示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// 创建数组
var myColor = [0, 1, 2, 3, 4]
// 设置颜色
function s() {
// 利用循环结构 对数组进行赋值
var txt;
for (let index = 0; index < myColor.length; index++) {
if (index == 0) {
var person = prompt("请输入第一个颜色");
if (person.length == 0 || person.trim() == '' || person == '') {
txt = "用户输入取消"
} else {
myColor[0] = person;
}
}
else if (index == 1) {
var person = prompt("请输入第二个颜色");
myColor[1] = person;
} else if (index == 2) {
var person = prompt("请输入第三个颜色");
myColor[2] = person;
} else if (index == 3) {
var person = prompt("请输入第四个颜色");
myColor[3] = person;
} else if (index == 4) {
var person = prompt("请输入第五个颜色");
myColor[4] = person;
}
}
}
// 显示颜色
function x() {
document.querySelector("#zero").value = myColor[0]
document.querySelector("#one").value = myColor[1]
document.querySelector("#two").value = myColor[2]
document.querySelector("#three").value = myColor[3]
document.querySelector("#four").value = myColor[4]
alert("您输入的颜色有"+myColor[0]+"&" +myColor[1]+"&" +myColor[2]+"&" +myColor[3]+"&" +myColor[4])
}
// 颜色排序
function p(){
myColor.sort(
function(a,b){
return b[0].charCodeAt()-a[0].charCodeAt()
}
)
document.querySelector("#zero1").value = myColor[0]
document.querySelector("#one1").value = myColor[1]
document.querySelector("#two1").value = myColor[2]
document.querySelector("#three1").value = myColor[3]
document.querySelector("#four1").value = myColor[4]
}
</script>
</head>
<body>
<form action="">
<table border="0">
<tr>
<td><input type="text" id="zero" value="">
</td>
<td><input type="text" id="zero1" value=""></td>
</tr>
<tr>
<td><input type="text" id="one"></td>
<td><input type="text" id="one1"></td>
</tr>
<tr>
<td><input type="text" id="two"></td>
<td><input type="text" id="two1"></td>
</tr>
<tr>
<td><input type="text" id="three"></td>
<td><input type="text" id="three1"></td>
</tr>
<tr>
<td><input type="text" id="four"></td>
<td><input type="text" id="four1"></td>
</tr>
</table>
<input type="button" name="设置颜色" value="设置颜色" id="button1" onclick="s()">
<input type="button" name="显示颜色" value="显示颜色" id="button2" onclick="x()">
<input type="button" name="颜色排序" value="颜色排序" id="button3" onclick="p()">
</form>
</body>
</html>