[英]HTML and Javascript, window.prompt
对javascript和html类型的东西非常新。 我只想举一个使用用户输入并将其输出到表中的简单示例。 我在获取窗口提示时遇到了麻烦。 我想我确实在做错事,但我目前还没有看到……我正在学校上课,但这不是家庭作业,只是我自己做的练习。
这与while循环有关吗? 关于我应如何继续提示用户直到他们另有说明的任何建议?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mileage Record</title>
<style type = "text/css">
table {
width:300px;
border-collapse:collapse;
background-color:lightblue;
}
table, td, th {
border: 1px solid black;
padding: 4px;
}
th {
text-align: left;
color: white;
background-color: darkblue
}
tr.oddrow {
background-color: white;
}
</style>
<script>
var milesDriven;
var gallonsUsed;
var mpg;
var anyMore;
document.writeln("<table>");
document.writeln("<thead><tr><th>Miles Driven</th>");
document.writeln("<th>Gallons Used</th>");
document.writeln("<th>MPG</th>");
document.writeln("</tr></thead><tbody>");
while (anyMore == true) {
milesDriven = window.prompt("How many miles did you drive?");
gallonsUsed = window.prompt("How many gallons did you use?");
mpg = milesDrive/gallonsUsed;
document.writln("<tr><td>" + milesDriven + "</td><td>" +
gallonsUsed + "</td><td>" + mpg + "</td></tr>");
anymore = confirm("Do you have any more data to input?");
}
document.writeln("</tbody></table>");
</script>
该方法存在几个问题。 您不应使用document.writeln()
来修改文档内容。 而是创建元素并将其添加到文档树中。 一个好的JavaScript教程应该告诉您如何做到这一点。 它还将解释标识符是区分大小写的,所以你不能只写anyMore
这里anymore
那里。 您在标识符中也有其他错别字。 而且,由于未定义的值不等于true
,因此永远不会执行循环。
<pre>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mileage Record</title>
<style type = "text/css">
table {
width:300px;
border-collapse:collapse;
background-color:lightblue;
}
table, td, th {
border: 1px solid black;
padding: 4px;
}
th {
text-align: left;
color: white;
background-color: darkblue
}
tr.oddrow {
background-color: white;
}
</style>
<script>
// var milesDriven;
// var gallonsUsed;
// var mpg;
var anyMore=0;
var str="<table>";
str+="<thead><tr><th>Miles Driven</th>";
str+="<th>Gallons Used</th>";
str+="<th>MPG</th>";
str+="</tr></thead><tbody>";
function milesDriven(){
return window.prompt("How many miles did you drive?");
}
function gallonsUsed(){
return window.prompt("How many gallons did you use?");
}
function mpg(){
return milesDriven()/gallonsUsed();
}
function addComponentsToDOM(){
while (anyMore<3) { //not 0 is true or not undefined is true or not null is true
str+="<tr><td>" + milesDriven() + "</td><td>" +
gallonsUsed() + "</td><td>" + mpg() + "</td></tr>"
// anymore = confirm("Do you have any more data to input?");
anyMore++;
}
str+="</tbody></table>";
//document.writeln(); i suggest you not use this method add component to DOM tree
//because this method first empty DOM tree content
document.body.innerHTML=str;
}
//why use this event,because window after loaded document.body not null
window.onload=addComponentsToDOM;
</script>
</pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.