简体   繁体   中英

Pass a function by variable to another function to be bound as a jQuery click event

I'm trying to pass a function via a variable to be assigned as part of a click event, for instance:

function bindClick(func) {
    $('#button').click(function() {
        func();
        return false;
    });
}

function configureClick() {
    bindClick(function () { executeClick(message); });
}

function executeClick(message) {
    alert(message);
}

So configureClick() will run at some point, and then #button.click() needs to call the contents of func .

Whatever's happening, is doing so silently, no errors nor desired behavior.

UPDATE : I'm an idiot! The code above is working. My executeClick had a switch-case block which was being ignored as I was passing the incorrect key. Sorry for the trouble D:

You do too much passing of callback function. That' creating lots of closures, which is not needed in such a simple case.

function bindClick(func) {
    $('#button').click(function() {
        func();
        return false;
    });
}


function executeClick(message) {
    alert(message);
}

function configureClick(message){
    bindClick(function(){ executeClick(message) });
}

configureClick('Hello');

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