[英]Multi Line Comments and/or Display
如何在浏览器中显示多行注释或消息? 例如,如果我希望用户单击一个框并让浏览器以问题#1-10的格式显示多行:
<!DOCTYPE html>
<html>
<body>
<h1>Mathematics Review</h1>
<p>Click Below For a Quick Review:</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo">Please Take Notes!</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Question #1";
}
</script>
</body>
</html>
最终,当用户单击“单击我”按钮时,问题应显示如下:
Question #1
Question #2
Question #3
Question #4
and so on....
另外,尝试实现此功能时,不同的浏览器的行为是否有所不同?
您可以在您的innerHTML
值中添加<br>
标记:
document.getElementById("demo").innerHTML = "Question #1<br>Question #2<br>Question #3<br>Question #4";
var count = 1; function myFunction() { document.getElementById("demo").innerHTML += "<br/>Question #"+(count++); }
<h1>Mathematics Review</h1> <p>Click Below For a Quick Review:</p> <button type="button" onclick="myFunction()">Click Me!</button> <p id="demo">Please Take Notes!</p>
您可以使用:
document.getElementById("demo").innerHTML += "<br/>Question #" + ++question;
question
是初始化为零的全局变量-请参见下面的演示:
var question = 0; function myFunction() { document.getElementById("demo").innerHTML += "<br/>Question #" + ++question; }
<h1>Mathematics Review</h1> <p>Click Below For a Quick Review:</p> <button type="button" onclick="myFunction()">Click Me!</button> <p id="demo">Please Take Notes!</p>
全局声明一个变量,单击计数,然后在运行myFunction时将其递增。
在其他方面,您应该提醒的是,在脚本标签之间保持注释,以避免在诸如Firefox,Chrome,IE等浏览器之间出现解析错误。
这是我为您提供的解决方案。
<!DOCTYPE html>
<html>
<body>
<h1>Mathematics Review</h1>
<p>Click Below For a Quick Review:</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo">Please Take Notes!</p>
<script language="JavaScript">
<!--
var clickcount = 1;
function myFunction() {
document.getElementById("demo").innerHTML = "Question #" + clickcount++;
}
-->
</script>
</body>
</html>
并且,如果您想要某种效果,例如在某个时间段内自动递增数字,则可以使用setInterval函数。
每次您单击按钮时,这是另一个具有10次迭代的视图。
<!DOCTYPE html>
<html>
<body>
<h1>Mathematics Review</h1>
<p>Click Below For a Quick Review:</p>
<button type="button" onclick="try10Iter()">Click Me!(10 iteration)</button>
<button onclick="myVar = setTimeout(try10Iter, 500)">Try it</button>
<button onclick="clearTimeout(myVar)">Stop it</button>
<p id="demo">Please Take Notes!</p>
<script language="JavaScript">
<!--
var clickcount = 1;
var countVar;
function stopIterAt(condition)
{
if(clickcount == condition)
{
clearInterval(countVar);
clickcount = 0;
}
}
function myFunction() {
document.getElementById("demo").innerHTML = "Question #" + clickcount++;
stopIterAt(11)
}
function try10Iter()
{
countVar = window.setInterval(myFunction, 500);
}
-->
</script>
</body>
我从网站上借了一些代码。
问候,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.