简体   繁体   English

JavaScript onClick更新Div

[英]JavaScript onClick update Div

JSFIDDLE 的jsfiddle

I am trying to update a few div's with new text every time a button is clicked. 我试图每次单击按钮时用新文本更新几个div。 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. 当我将我希望它直接执行的操作放在onClick事件中时,它将起作用。 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. 或者在您的JS中,只需定义“更新”函数,而不是将其声明为一个函数即可。 Check out this fiddle where it works: https://jsfiddle.net/vhw8xewy/6/ 看看这个小提琴在哪里工作: https : //jsfiddle.net/vhw8xewy/6/

update = function() {
   ...
}

instead of 代替

function update() {
   ...
}

This is because the JavaScript is running before the HTML has finished loading. 这是因为在HTML完成加载之前,JavaScript正在运行。

Change the Fiddle to run the JavaScript in the body. 更改小提琴以在体内运行JavaScript。

In the drop-down on the left of the Fiddle where is says onLoad - change this to No wrap - in <body> . 在上哪里是小提琴左侧的下拉说onLoad -这种改变No wrap - in <body>

Your code will work as is. 您的代码将按原样工作。

See here: https://jsfiddle.net/vhw8xewy/8/ 看到这里: https : //jsfiddle.net/vhw8xewy/8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM