简体   繁体   中英

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

document.getElementById('click').addEventListener('click',funto);

Your code var fun = funto() need change to 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. Of course, if you ain't using them anywhere else.

So the JS code may look something like this:

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

and HTML, then, should look like this:

<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.

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.

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