user1788736
user1788736

Reputation: 2845

How to use javascript variables to set image source and image title?

all. I have the following JavaScript variable strVar. I want to use variables to set the src attribute and the image title.

 var strVar="";
    strVar += "<img src=\"http:\/\/somesite.com\/3\/ok\/images\/123456.png\"\/><b>mango<\/b><br><span class=\"centerKeyContainer\">";

I want to use variables like this:

var strVar="";
strVar += "<img src=\""+imageSource+""\/><b>"+imageTitle+<\/b><br><span class=\"centerKeyContainer\">";

But the above keeps giving me a syntax error! Could anyone tell me how to fix it? Thanks in advance.

Upvotes: 0

Views: 269

Answers (3)

Nikolay Ermakov
Nikolay Ermakov

Reputation: 5061

  1. Second slash is wrongly escaped
  2. Missing quote after imageTitle
  3. Don't need to escape slash before closing /b

    strVar += "<img src=\""+imageSource+"\"/><b>"+imageTitle+"</b><br><span class=\"centerKeyContainer\">";
    

Upvotes: 2

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

var strVar="";
strVar += "<img src=\""+imageSource+""\/><b>"+imageTitle+<\/b><br><span class=\"centerKeyContainer\">";

Here the quotes after the "imageSource" variable name are not escaped correctly. The second quote should be escapes as below and the code should look like this

strVar += "<img src=\""+imageSource+"\"/><b>"+imageTitle+"</b><br><span class=\"centerKeyContainer\">";

Upvotes: 0

Joel
Joel

Reputation: 324

Missing escape character for the double quote after imageSource. Missing a double quote after imageTitle.

strVar += "<img src=\""+imageSource+"\"\/><b>"+imageTitle+"<\/b><br><span class=\"centerKeyContainer\">";

Upvotes: 0

Related Questions