我有一个更改段落内容的函数:
function test() {
document.getElementById("demo").innerHTML = "ops2"
}
在标签内使用时效果很好:
<button type="button" onclick='document.getElementById("demo").innerHTML = "ops"'>Change Content</button>
但是当放置在函数外部时它不起作用:
<button type="button" onclick=test()>load</button>
这是jsfiddle。我做错了什么?
答案 0 :(得分:0)
它只是脚本和HTML代码序列的问题。当我将test
函数置于html代码之上,然后使用onclick="test()"
调用该函数时,它运行良好。
以下是我所做的:(请注意Change Content
按钮标记。)
<script>
function test(){
document.getElementById("demo").innerHTML = "ops2"
}
</script>
<h3 id="demo">Hello</h3>
<p>Here is some text</p>
<center>
<img id="lamp" src="https://www.w3schools.com/js/pic_bulboff.gif"/>
<br/><br/><br/>
<button type="button" onClick='test()'>Change Content</button>
<br/><br/><br/>
<button type="button" onClick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulbon.gif"'>Light</button>
<button type="button" onclick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulboff.gif"'>Dark</button>
<button type="button" onclick='document.getElementById("lamp").src = ""'>Hide</button>
<button type="button" onclick='document.getElementById("lamp").src = "https://www.w3schools.com/js/pic_bulboff.gif"'>Show</button>
</center>