I am trying to update a few div's with new text every time a button is clicked. I have tried many things it seems that the function isn't even being called. When I put what I want it to do directly in the onClick event it works. It just doesn't work when I call a method.
It works when I do this.
<button onClick="document.getElementById('title').innerHTML = 'Some Title'">Click me</button>
But when I try to do this.
<button onClick="update(0);">Click me</button>
It doesn't work.
Thanks for the help in advance.
尝试
onClick="(function(){document.getElementById('title').innerHTML = 'Some Title'})()"
Or in your JS just define the "update" function instead of declaring it as a function. Check out this fiddle where it works: https://jsfiddle.net/vhw8xewy/6/
update = function() {
...
}
instead of
function update() {
...
}
This is because the JavaScript is running before the HTML has finished loading.
Change the Fiddle to run the JavaScript in the body.
In the drop-down on the left of the Fiddle where is says onLoad
- change this to No wrap - in <body>
.
Your code will work as is.
See here: https://jsfiddle.net/vhw8xewy/8/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.