Reputation: 642
The scenario is the following: I call the buldMyStuff function to build images many times the following way. Wrapping the img into an "a" tag is not an option.
function buildMyStuff(item){
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
return tag;
}
function doClick(type,data){
//do stuff
}
Lets assume that the item.type value is "type" and the item.data value is "data". The problem with this that when I click the image it says type is not defined. Therefore (and I checked in the built html structure) the img eventually looks like this:
<img src="someimg.png" onclick="doClick(type,data)" />
What I need to achieve is:
<img src="someimg.png" onclick="doClick('type','data')" />
However as I am using the ' character to wrap the whole tag and the " character to wrap the attribute I cannot use anything else. Does someone know the solution for this?
Thank you in advance.
Upvotes: 0
Views: 99
Reputation: 24276
function buildMyStuff(item){
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
return tag;
}
Upvotes: 1
Reputation: 6849
You can use '\'
to escape special characters.
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
=>
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
Upvotes: 1
Reputation: 4173
this is invalid;
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
It should be
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
Upvotes: 1