我需要这个来接受用户输入。取值并减去一个,以便可以调用和打印5个阵列中的一个。如果选择5,则打印所有5个阵列;如果选择3,则打印数组0到2。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test2</title>
</head>
<body>
<input type="button" onclick="dutyarray()" value="Click">To see my top<input type="number" id="counter"> job duties here</input>
<br />
<p id="task">Duties</p>
<script>
function dutyarray()
{
var x = document.getElementById('counter').value;
x = parseInt(x);
var duty= new Array();
duty[0] = "Operate Equipment";
duty[1] = "Check for Water Damage";
duty[2] = "Check for Mold";
duty[3] = "Follow Insurance Procedure";
duty[4] = "Restore";
while(x >= 0; x - 1)
{
document.getElementById('task').innerHTML = duty[x] + <br>;
}
}
</script>
答案 0 :(得分:2)
您可以使用
var duty = [
"Operate Equipment",
"Check for Water Damage",
"Check for Mold",
"Follow Insurance Procedure",
"Restore"
],
x = parseInt( document.getElementById('counter').value, 10 );
document.getElementById('task').innerHTML = duty.slice(0, x).join('<br />');
备注强>
使用parseInt
或parseFloat
时,请始终使用第二个参数(基数)。
如果document.getElementById('counter').value
是数字字符串(例如'3'
),请不要使用parseInt
。相反,如有必要,请使用+'3'
获取号码3
。
如果您要将parseInt
之类的内容解析为'3px'
,请仅使用3
。
不要在循环的每次迭代中使用getElementById
来获取相同的元素。
然后,而不是
for(var i = 0; i < n; ++i) {
doSomething(document.getElementById('foo'), i);
}
使用
var el = document.getElementById('foo');
for(var i = 0; i < n; ++i) {
doSomething(el, i);
}
永远不要在循环的每次迭代中更改innerHTML
,因为修改DOM会导致性能不佳。
然后,而不是
for(var i = 0; i < n; ++i) {
element.innerHTML += someHTML(i); // n DOM modifications
}
使用
var html = '';
for(var i = 0; i < n; ++i) {
html += someHTML(i);
}
element.innerHTML = html; // only 1 DOM modification
答案 1 :(得分:0)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test2</title>
</head>
<body>
<input type="button" onclick="dutyarray()" value="Click">To see my top
<input type="number" id="counter"> job duties here</input>
<br />
<p id="task">Duties</p>
<script>
function dutyarray() {
var x = document.getElementById('counter').value;
x = parseInt(x);
var duty =
[
"Operate Equipment",
"Check for Water Damage",
"Check for Mold",
"Follow Insurance Procedure",
"Restore"
];
if (x > duty.length-1) x = duty.length-1; // Performs some checking
document.getElementById('task').innerHTML = "";
for ( ; x >= 0; x--) {
document.getElementById('task').innerHTML += duty[x] + "<br>";
}
}
</script>
</body>
</html>