TheRealPapa
TheRealPapa

Reputation: 4539

Javascript to build HTML

this one may be simple but it has eluded me. I have Javascript code which builds elements in the DOM (using JSON from a server script). Some of the elements have "onclick" calls that I want to pass the ID variable to.

I cannot seem to get the onclick="downloadImg("' + d.data_id + '")" syntax right. What should it be. The code below does not work. Thanks.

temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg("' + d.data_id + '")">';

Upvotes: 0

Views: 58

Answers (4)

CMPS
CMPS

Reputation: 7769

If you use the double quotations, you will close the previous one, so you create a conflict. So replace " with a single quotation + escape \' like this:

temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg(\'' + d.data_id + '\')">';

Upvotes: 1

Samuel Cook
Samuel Cook

Reputation: 16828

Change your double quotes to single quotes and escape them:

onclick="downloadImg(\'' + d.data_id + '\')"

Upvotes: 0

Malk
Malk

Reputation: 11993

<img src="/link/to/img.png" onclick="downloadImg("' + d.data_id + '")">';

This will resolve to something like: <img src="/link/to/img.png" onclick="downloadImg("1")">

As you can see you have double quotes inside double quotes. Something like this should do it:

<img src="/link/to/img.png" onclick="downloadImg(\'' + d.data_id + '\')">

Upvotes: 0

tristantech
tristantech

Reputation: 66

Your line should be:

temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg(\\"' + d.data_id + '\\")">'; 

You basically have many layers of quotes so the double slash
creates a \" in the output that escapes the quote once it gets outputted to HTML

Upvotes: 0

Related Questions