繁体   English   中英

我想在变量中存储一个 function 并想在 onclick 事件中调用它

[英]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;">

如果要将变量设置为事件,可以使用addEventListener作为

document.getElementById('click').addEventListener('click',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;">

首先,欢迎来到社区。 其次,我建议您简化代码。 而不是在 function 之外有变量,而是将它们放在其中。 当然,如果您不在其他任何地方使用它们。

所以 JS 代码可能看起来像这样:

 function fun() {
      document.getElementById('GFG_DOWN_1') = 'From function 1';
    }

那么 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;">

请注意,您在 onclick 中调用onclick ,而不是变量。

暂无
暂无

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

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