简体   繁体   中英

Passing variable to ON method (in jquery)

I'm trying to pass a variable(present in global scope) to a function(present in on method). I'm passing a data object to the on but it's not working. It's working if i take variable inside the function.

Here's the code:

var firstName = $("#firstName").val();
$("#firstName").on("blur keyup paste", {firstName: firstName}, function(){
    //access firstName
})

Also, what is the best way of using on method. Should i use it like i have used above or should i use it like this?

var firstName = $("#firstName").val();
$(document).on("blur keyup paste", "#firstName", {firstName: firstName}, function(){
    //access firstName
})

As the event is being raised on the element which has the value you're trying to retrieve you can use the this reference to get at it:

$("#firstName").on("blur keyup paste", function(){
    var firstname = this.value; // or $(this).val();
});

With regard to the usage of on , your first example is to be used when the element you're attaching the event to exists in the DOM. The second method is for when the element does not yet exist, but may do in the future. You should use the nearest static parent element for the primary selector though, not document .

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