我开始从W3scholl学习javascript。我想从这个tutorial创建按钮:
<html>
<body>
<h1>My First JavaScript</h1>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
我想再次按下按钮后清除日期文本,怎么做?
答案 0 :(得分:0)
你可以像这样添加一个新按钮:
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.
</button>
<button type="button" onclick="Empty()">
Click me to delete Date and Time.
</button>
<script>
function Empty(){
document.getElementById('demo').innerHTML = "";
}
</script>
<p id="demo"></p>
</body>
</html>
答案 1 :(得分:0)
您可以引入全局变量state
并保存上次更改的状态。
单击按钮调用toggle
,函数将评估state
以进行下一步操作。函数state
的末尾随logical NOT !
更改。
function toggle() {
if (state) { // check state
document.getElementById('demo').innerHTML = '';
document.getElementById('button1').innerHTML = 'Click me to display Date and Time.'
} else {
document.getElementById('demo').innerHTML = Date();
document.getElementById('button1').innerHTML = 'Delete Date and Time.'
}
state = !state; // toggle state
}
var state; // undefined, becomes later true and false
<button id="button1" type="button" onclick="toggle()">Click me to display Date and Time.</button>
<p id="demo"></p>