简体   繁体   English

如何使用JavaScript处理html按钮元素的“ onclick”事件?

[英]How to manipulate the “onclick” event of a html button element with JavaScript?

document.getElementById("RightButton").innerHTML="Back to Question";
document.getElementById("RightButton").onclick=GoBack();

Is the code I wrote to solve my problem. 是我为解决问题而编写的代码。 The first line successful changed the name of the button, but the second line simply doesn't work. 第一行成功更改了按钮的名称,但是第二行根本不起作用。

As you may have discovered, I'm totally a newbie. 您可能已经发现,我完全是新手。 If you use excessive jargon, it will probably take me another question to figure out the jargon. 如果您使用过多的行话,则可能需要我再问一个问题来弄清楚行话。

Just remove the () . 只需删除() That way, you pass the function itself rather than calling it. 这样,您可以传递函数本身而不是调用它。

GoBack is a function. GoBack是一个函数。 Assign the function reference to the onclick property, but don't execute it immidiately with () . 将函数引用分配给onclick属性,但不要立即执行() That way you assign the result of the call as the handler, not the function-to-be-executed when the element is clicked. 这样,您可以将调用结果分配为处理程序,而不是单击元素时要执行的函数。 Read more on event registration here . 此处阅读有关事件注册的更多信息

var button = document.getElementById("RightButton");
button.innerHTML = "Back to Question";
button.onclick = GoBack;

As a note, conventionally only constructor functions use uppercase letters. 注意,常规上仅构造函数使用大写字母。

You are calling the GoBack() function instead of assigning it to to the onclick event. 您正在调用GoBack()函数,而不是将其分配给onclick事件。 Change your code to the below and you should be all set. 将您的代码更改为以下代码,您应该已经准备就绪。

document.getElementById("RightButton").onclick=GoBack;

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

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