简体   繁体   中英

javascript syntax - passing variable to function

var testvar = "something";

//only one of the following 3 lines were uncommented while testing:
var myinsert = '<span class="green myCursor" 
                   onClick="getproblemsadmin(testvar)">
                   Test
                </span>'; //doesn't pass testvar to function

var myinsert = '<span class="green myCursor" 
                   onClick="getproblemsadmin(\'testvar\')">
                   Test
                </span>'; //doesn't pass testvar to function

var myinsert = "<span class='green myCursor' 
                   onClick='getproblemsadmin(\"testvar\")\'>
                   Test
                </span>"; //doesn't pass testvar to function

$('.someclass').html(myinsert); //jquery works and this works (tested)

Is there a way to pass a variable to function like this?

Do you mean the value of this variable?

var myinsert = "<span class='green myCursor' onClick='getproblemsadmin(\""+testvar+"\")\'>Test</span>";

The syntax:

var myinsert = "string" + variable + "string";
var myinsert = 'string' + variable + 'string';

You could try creating the span element and then binding the click event:

$('<span class="green myCursor">Test</span>').click(function()
{
    getproblemsadmin('testvar')
});

or, if you wanted to get really jQuery'esk, you could write:

$('<span />').addClass('green myCursor').text('test').click(function()
{
    getproblemsadmin('testvar')
});

If I understood you correctly you are looking for a way to pass a variable to a function which will return a constructed string containing markup code? Something like this?

var testvar = "something";

var myinsert = work_horse(testvar);
$('.someclass').html(myinsert);

function work_horse(testvar){
    return '<span class="green myCursor" onClick="getproblemsadmin(' + testvar + ')">Test</span>';
}​

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