0

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.

3 Answers 3

1

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+ '\')" />';

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Markus. I figured out after Matei Mihai's answer. He's solution was not correct, but yours is. Thanks guys.
1

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+ '\')" />';

2 Comments

But in that case the img will be: <img src="someimg.png" onclick="doClick("type","data")" />. That does not seem to be valid for me.
It looks like it, but in reality its "doClick('type','data')" the quotes are single but with a \ infront, this escapes the ' making it "doClick('type','data')"
1
function buildMyStuff(item){ 
    var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />'; 
    return tag; 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.