简体   繁体   English

使用JavaScript在事件(onclick)调用的函数中使用参数

[英]using an argument in a function called by an event (onclick) using JavaScript

I'm trying to create an onclick event using JavaScript. 我正在尝试使用JavaScript创建一个onclick事件。 I would like the onclick event to trigger a function. 我想onclick事件触发一个函数。 What I'm finding is that if I call the function without an argument or the parenthesis, the function is called when the element is clicked. 我发现如果我在没有参数或括号的情况下调用函数,则在单击元素时调用该函数。

But if I try adding an argument to the function, the function is called immediately, before the element is even clicked. 但是如果我尝试向函数添加一个参数,则在单击元素之前立即调用该函数。

What I've discovered is that if I use an anonymous function, and place the function that I want to be called by the onclick event within the anonymous function, it works! 我发现如果我使用匿名函数,并在匿名函数中放置我想要被onclick事件调用的函数,它就可以了!

I don't understand why. 我不明白为什么。 There has to be something about the logic that I'm missing. 必须要有一些关于我缺少的逻辑。

I'm new to programming, and I would greatly appreciate any help in understanding why I can't simply call a function with an argument from an onclick event. 我是编程的新手,我非常感谢理解为什么我不能简单地用onclick事件中的参数调用函数。 Thanks 谢谢

Here is the code I have that works 这是我的代码有效

window.onload = init;

function init() {
    var divSelect = document.querySelector(".basic");
    divSelect.onclick = function () {addRed(divSelect)};

}

function addRed(el) {
    var divClass = el.getAttribute("class");

    if (divClass == "basic red") {
        el.setAttribute("class", "basic");
    }
    else {

        el.setAttribute("class", "basic red");
    }
}

If you're doing divSelect.onclick = addRed(divSelect); 如果你正在做divSelect.onclick = addRed(divSelect); what's happening is that it calls addRed(divSelect) , and sets the return value of that as the onclick . 发生的事情是它调用addRed(divSelect) ,并将其返回值设置为onclick That's all fine if you actually return the function you want, but in most cases, it's not. 如果您实际返回所需的功能,那就没关系了,但在大多数情况下,并非如此。 That's why you need to wrap it in an anonymous function. 这就是你需要将它包装在一个匿名函数中的原因。

The other option is to use Function.bind() : 另一种选择是使用Function.bind()

divSelect.onclick = addRed.bind( // bind a context and pre-fill arguments
    divSelect, // the context, can be anything in this case
    divSelect); // the pre-filled argument

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

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