function is being called automatically in JS

huangapple go评论63阅读模式
英文:

function is being called automatically in JS

问题

I was trying to create a parameterized function using JS, I started code with a window.onload=()=>{}, and the syntax for my function is function name(arg){}.

我试图创建一个带参数的 JavaScript 函数,我从 window.onload=()=>{} 开始编写代码,函数的语法是 function name(arg){}

I want to call this function on a click event. so my statement goes btn.onclick=function_name(arg); . but, the function gets called as soon as the page loads, without a click. What can i do to solve this problem?

我想在点击事件上调用这个函数,所以我的语句是 btn.onclick=function_name(arg);,但是函数在页面加载时立即被调用,而不需要点击。我该怎么解决这个问题?

英文:

I was trying to create a parameterized function using JS, I started code with a window.onload=()=>{},
and the syntax for my function is function name(arg){}.

I want to call this function on a click event. so my statement goes btn.onclick=function_name(arg); . but, the function gets called as soon as the page loads, without a click. What can i do to solve this problem?

window.onload = () => {
  var btn .....

  btn.onclick = func(arg..);

  function func(arg){
  }
}

答案1

得分: 1

btn.onclick = func(arg..); 调用该函数并将返回值赋给btn的onclick属性。

附加一个事件监听器到按钮上,使用这段代码片段。你可以使用data-属性向按钮添加数据。

<!-- 开始代码片段: js 隐藏: false 控制台: true babel: false -->

<!-- 语言: lang-js -->

document.getElementById("btn").addEventListener("click", fn);

function fn(e) {
  this.textContent = "Clicked " + this.dataset.arg;
}

<!-- 语言: lang-html -->

<button id="btn" data-arg="arg">Click</button>

<!-- 结束代码片段 -->
英文:

btn.onclick = func(arg..); calls the function and assigns the return value to the onclick property of btn.

Attach an event listener to the button with the snippet code. You can use data- attributes to add data to the button.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.getElementById(&quot;btn&quot;).addEventListener(&quot;click&quot;, fn);

function fn(e) {
  this.textContent = &quot;Clicked &quot; + this.dataset.arg;
}

<!-- language: lang-html -->

&lt;button id=&quot;btn&quot; data-arg=&quot;arg&quot;&gt;Click&lt;/button&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月11日 08:21:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定