简体   繁体   中英

How to pass an object as parameter to an onClick function using Jquery

I have an object that I need to pass to a function, this function is trigger via onClick and onKeyUp() , but I couldn't make it work.
Although I can pass values to it.

function myFunc(myObj) {

 $("<button type="button" onclick='otherFunction( $(\"#elem\").val() )'
onkeyup='otherFunction( $(\"#elem\").val() )'> CLICK IT </button>"
} 

As you can see, i have a otherFunction and I Can pass the $("#elem").val() as a parameter. But I need to also pass myObj to it.
Tried everything I could think of and I was unable to make it work.

Obs: myObj is a marker from googleMaps, so I can't just pass it's attributes values. I need to access the full object on my second function. Because I need to do something like: myObj.setOptions(.....)

As you are using jQuery to create button, use .on() to bind event handler's. The object myObj will be accessible in the event handler due to closure

function myFunc(myObj) {
    var button = $('<button>', {
            "type": "button",
            "text": "CLICK IT"
        }).on('click keyup', function () {
            // myObj will be accessible here
            otherFunction($("#elem").val());
        });
}

A good read How do JavaScript closures work?

this code explained how you send data to the handler with jQuery

$('yourElement').click(yourData, function(eventObject){
    var thisIsYourData = eventObject.data;
})

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