![](/img/trans.png)
[英]I want to disabled onClick event for image inside div onClick function?
[英]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.