[英]I want to store a function in variable and want to call that at onclick event
var down_1 = document.getElementById('GFG_DOWN_1'); var fun = funto(); function funto() { down_1.innerHTML = 'From function 1'; }
<h1 style="color:green;">GeeksforGeeks</h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"></p> <button onclick="fun">click here</button> <p id="GFG_DOWN_1" style="color:green; font-size: 20px; font-weight: bold;">
If you want to set variable to event, you can use addEventListener
as如果要将变量设置为事件,可以使用
addEventListener
作为
document.getElementById('click').addEventListener('click',funto);
Your code var fun = funto()
need change to var fun = funto;
您的代码
var fun = funto()
需要更改为var fun = funto;
var down_1 = document.getElementById('GFG_DOWN_1'); var fun = funto; function funto() { down_1.innerHTML = 'From function 1'; } document.getElementById('click').addEventListener('click',funto);
<h1 style="color:green;">GeeksforGeeks</h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"></p> <button id="click">click here</button> <p id="GFG_DOWN_1" style="color:green; font-size: 20px; font-weight: bold;">
First, welcome to the community.首先,欢迎来到社区。 Second, I would suggest you simplify your code.
其次,我建议您简化代码。 Instead of having variable outside function put them inside of it.
而不是在 function 之外有变量,而是将它们放在其中。 Of course, if you ain't using them anywhere else.
当然,如果您不在其他任何地方使用它们。
So the JS code may look something like this:所以 JS 代码可能看起来像这样:
function fun() {
document.getElementById('GFG_DOWN_1') = 'From function 1';
}
and HTML, then, should look like this:那么 HTML 应该如下所示:
<h1 style="color:green;">GeeksforGeeks</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;"></p>
<button onclick="fun();">click here</button>
<p id="GFG_DOWN_1" style="color:green; font-size: 20px; font-weight: bold;">
Please notice that you are calling a function in onclick
, not a variable.请注意,您在 onclick 中调用
onclick
,而不是变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.