我是JavaScript的初学者。目前,我正在学习按钮,警报和编写文档。对于一个有趣的小项目,我想按一个按钮,然后将其写入文档。效果很好,但是我要按下其他按钮,但是我不知道如何“返回”另一页并按下其他按钮。我如何才能使按钮“返回”或使用计时器?哪个会更容易?一旦进入其他页面,我就不想呆在那里。
示例:
function myTest1() {
document.write("JavaScript")
}
<input type="button" onClick="myTest1()" value="What language is this?">
答案 0 :(得分:1)
通过将按钮保留在容器中,将显示的“页面”保留在另一个容器中:
type T40 = FunctionPropertyNames<Part>;
function myTest1() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "JavaScript";
}
function goBack() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "Click a button to change this content";
}
或通过同时更改按钮和内容:
<div id="button-container">
<input id="which-language-btn" type="button" onclick="myTest1()" value="What language is this?">
<input id="bo-back-btn" type="button" onclick="goBack()" value="Go back" />
</div>
<div id="content" style="border: 1px solid;">
Click a button to change this content
</div>
function myTest1() {
// document.getElementBy('content') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "JavaScript<input type=\"button\" onclick=\"goBack()\" value=\"Go back\" />";
}
function goBack() {
// document.getElementBy('button-container') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "Click a button to change this content<input id=\"which-language-btn\" type=\"button\" onclick=\"myTest1()\" value=\"What language is this?\">";
}
这个想法是使用innerHTML而不是document.write来避免替换所有文档(包括脚本)
答案 1 :(得分:0)
document.write
clears the document when it's called:
注意:当document.write写入文档流时,在关闭的(已加载)文档上调用document.write会自动调用document.open,这将清除文档。
您可以仅继续将输出附加到主体,但从长远来看,调整单独的div内容(用于输出)要好得多,而不仅仅是保持主体。
function myTest1() {
document.getElementById('output').textContent += "JavaScript\n"
}
#output {
width: 100%;
min-height: 20px;
background-color: rgb(20, 20, 30);
color: white;
margin-top: 20px;
font-family: "Lucida Console";
padding: 5px;
}
<input type="button" onClick="myTest1()" value="What language is this?">
<div id="output">
</div>