brother
brother

Reputation: 8171

Escaping variables for a function call?

In a function, i am building a string. The string is some content for a popup (google maprs info window). The code looks like this;

var windowcontent = "<strong>Something</strong><br/>" + somethingVar + "<br/><br/>";
windowcontent += "<a href='javascript:goto('\"+var1+\"','\"+var2+\"');'>Goto</a>";

The problem is the link and the variables i want to include in the function call. Whatever i try, i cant seem to get it to work. I know it is something with escaping the correct way, but i have not found the correct way yet, it seems.

How should the string, with the link in it, look?

Upvotes: 0

Views: 50

Answers (1)

gurvinder372
gurvinder372

Reputation: 68433

Second line should be

windowcontent += "<a href='javascript:goto(\'" + var1 +"\',\'"+ var2 + "\');'>Goto</a>";

Basically you need to escape the single quote rather than double quote.

Updated code after discussion, demo

var var1 =  encodeURI("(56.02, 9.27)") ;
var var2 =  encodeURI("(56.02, 9.27)") ;

window.addEventListener("load", function()
{
    document.body.innerHTML += '<a  data-var1="' + var1 + '" data-var2="' + var2 + '" href="#" onclick="goto(this)"> Goto </a>';
    console.log(document.body.innerHTML);
}, false);

function goto (thisObj) 
{ 
   console.log(thisObj);
   var var1 = thisObj.getAttribute( "data-var1" );
   var var2 = thisObj.getAttribute( "data-var2" );
    console.log(var1 + ' - ' + var2); 
}

Upvotes: 2

Related Questions