2

I am trying to get the src of an image to be based on sky+gatMap()+.jpg The src is supposed to be sky#.jpg where # is the value of getMap(). I am having trouble with the quotation or something, what am I doing wrong here?

<script type="text/javascript">
    document.write("<img id='sky' src='sky+mapNum()+.jpg' alt='' />");
  </script>

This is a case problem out of a javaxcript book. It doesn't tell me how to do this.

2
  • I am well aware it has to have something to do with quotations, but I couldn't figure out the right combination. Commented Jul 1, 2013 at 2:30
  • document.write("<img id='sky' src='sky"+mapNum()+".jpg' alt='' />"); Commented Jul 1, 2013 at 2:31

6 Answers 6

4
document.write('<img id="sky" src="sky' + mapNum() + '.jpg" alt="" />');

That should do it. Open/close your quotes as needed. Use different quotes for literal string quotes and end-of-string-literal quotes, or escape with \ as needed.

I should also point out that document.write() usage is generally discouraged. Consider manipulating the DOM in some other way. Also, if you are returning any arbitrary string from mapNum(), you may be generating invalid HTML, and may even open up yourself to XSS attacks if that value can come from a request parameter. You should edit the attribute of an element directly instead, when possible.

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

Comments

3
<script type="text/javascript">
  document.write("<img id='sky' src='sky"+mapNum()+".jpg' alt='' />");
</script>

1 Comment

Thank you, I have to wait 10 min to say question answered.
1

<script type="text/javascript"> document.write("<img id='sky' src='sky"+mapNum()+".jpg' alt='' />"); </script>

u need to break the string before + plus sign by putting a double qoutation mark and then start it again after the next plus sign.

Comments

0

Your variables are included in the string and is being interpreted as HTML and not JavaScript. Try this:

<script type="text/javascript">
  document.write("<img id='sky' src='sky" + mapNum() + ".jpg' alt='' />");
</script>

Comments

0

after puting " " quotes it becomes a string it means it will not print any value it will just print as it is written. so you should keep in mind to where to use " " quotes.

<script type="text/javascript">
document.write("<img id='sky' src='sky'"+mapNum()+".'jpg' alt='' />");
</script>

Comments

0
<script type="text/javascript">
    document.write("<img id='sky' src='sky" + mapNum + ".jpg' alt='' />");
</script>

mapNum is a variable not a function so no () after it. The book very vague.

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.