jquery .on() pass data through function

纵然是瞬间 提交于 2019-12-24 03:07:26

问题


I am reading the .on() jquery documentation.

And is it possible to pass some data like this:

function greet( event ) {
 alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {name: "Karl"}, greet );

The prototype of the methos is:

$(selector).on(event,childSelector,data,function,map)

Is it possible to have a more complex thin instead of only a string into the data parameter?.

In my case: I will be generating dynamically some popups with a number input inside and some text.

Is it possible to capture the information inside the caller popup, i.e. the number and the text of the caller popup. Maybe something like this:

$(document).on('click', '#id', 
var data =[
var number = functionThatGetTheNumberOfThePopup
var test = captureTextOfPopup
] , 
function(event){
//use number
//use test
});

回答1:


Yes, you can pass arbitrary data. You do it in the form of an object:

$(document).on('click', '#id', {
        number: functionThatGetTheNumberOfThePopup,
        test: captureTextOfPopup
    },
    function(event){
    //use number
    console.log(event.data.number);
    //use test
    console.log(event.data.test);
});



回答2:


You're example does pass something more complex than a "simple string" - you're example passes an object with one property name - there's no reason this couldnt be an object with 2 (or more) properties:

$(document).on('click', '#id', 
{
    number : functionThatGetTheNumberOfThePopup(),
    test : captureTextOfPopup()
} , 
function(event){
//use number
//use test
});


来源:https://stackoverflow.com/questions/20270791/jquery-on-pass-data-through-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!