简体   繁体   中英

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

I'm trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. 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!

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. 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); what's happening is that it calls addRed(divSelect) , and sets the return value of that as the 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() :

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

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