我尝试在用户输入“退出”后向页面添加项目符号列表;该清单不应包括“退出”一词。我能够使用document.write完整地获取列表,但这包括'退出'并摆脱了我的页面格式。我很确定我需要使用innerHTML,但是当我这样做时,我得到的是没有任何数组项的页面。非常感谢任何帮助。
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
答案 0 :(得分:1)
你必须使用 document.getElementById(),并在循环中生成一个字符串,并在循环后使用内部html,这样以前的li就不会重写。
更新代码部分,如
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
并在html中,删除ul和giv id中的div到ul
<ul id="results">
</ul>
以下是完整的代码:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
答案 1 :(得分:0)
您应该使用MyList.innerHTML += "<li>"+list+"</li>";
(请注意使用+=
代替=
)
另外,将您的<ul>
HTML更改为:
...
<ul id="results">
</ul>
...