简体   繁体   中英

Passing two parameters to a function

I try to send a javascript function 2 parameters like this:

var par1;
var par2;

$('#somediv').append('<div onclick="somefunction('+par1+','+par2+');"></div>');

i'm creating a lot of divs like this one and all dynamicaly, i just need to find the correct way to pass the par1 and par2 to the operate them later.

right now only par1 is ok, par2 is undefined (they both has string value).

Any suggestions?

这是因为par1和par2在您的代码中未定义。

用一些默认值初始化var1var2

The correct way to do fancy stuff like this is using .live , .delegate , or .on in jQuery.

var par1; // assuming these get values at some point
var par2; // assuming these get values at some point
$('#somediv').append('<div class='fancyDiv'></div>');
$('#somediv').on("click", ".fancyDiv", function() {
   someFunction(par1, par2);
}))

// use delegate instead of on if you're in jQuery 1.6 or lower
$('#somediv').delegate(".fancyDiv", "click", function() {
   someFunction(par1, par2);
}))

Use jQuery onclick eg

var par1 = 'par1';
var par2 = 'par2';

$('<div>Click</div>').appendTo('#somediv').click(function(){
    somefunction(par1, par2)
})

function somefunction(v1, v2){
    alert(v1+" "+v2);
} 
​

See it in action http://jsfiddle.net/anuraguniyal/gjz72

But it depends from where you are getting par1 and par2, if they are related to div and you need to have different one for each div, you should add them in html as data attribute eg

$('<div data-par1="par1" data-par2="par2" >Click</div>').appendTo('#somediv').click(somefunction)

function somefunction(){
    alert($(this).attr('data-par1')+" "+$(this).attr('data-par2'));
} 
​

See it in action http://jsfiddle.net/anuraguniyal/gjz72/14/

perimeterBox is function here

var perimeterBox = function(length,width)
{
    return length+length+width+width;
};

perimeterBox(5,5);

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