英文:
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("btn").addEventListener("click", fn);
function fn(e) {
this.textContent = "Clicked " + this.dataset.arg;
}
<!-- language: lang-html -->
<button id="btn" data-arg="arg">Click</button>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论