0

I asked a question a while back about how to get the current variable in a loop and I got the solution :

 for (i in ...)
 {
 ...
 href:"javascript:on_click('+i+');"...}

When i run this, the loop is sending the on_click function the string 'i' instead of the value of i.
Am I using the +variable+ wrong? Can someone explain in more detail what wrapping a variable in + means and why it is not working in my case?

asked Mar 23, 2011 at 19:19

4 Answers 4

1

Yes, you are - if you start a string with ", you have to end it with " (and vice versa for '), too. The syntax highlighting here at SO demonstrates this quite well too.

 href:"javascript:on_click("+i+");"...}

(What is happening is that ' within a string surrounded by " is treated as regular ' character, it does not start nor end a string literal here).

answered Mar 23, 2011 at 19:20
Sign up to request clarification or add additional context in comments.

2 Comments

what is it called when i do +i+? I'd like to look up more information on it except I don't know what to search up
What happens is that i is converted to a string and concatenated to the surrounding strings.
0

Try this:

href:"javascript:on_click('" + i + "');"
answered Mar 23, 2011 at 19:21

2 Comments

YESSS thank you so much! I've been trying to figure this out for so longggg. Could you explain why this works?
Look at this tutorial: quirksmode.org/js/strings.html pretty neat code examples there, that should give you the right idea.
0

Appears that you are missing double quotes to close your string. Javascript doesn't do variable interpolation in a quoted string.

Try:

href:"javascript:on_click('" + i + "');"...}
answered Mar 23, 2011 at 19:21

Comments

0

You're mixing your quote marks.

It should be:

href: "javascript:on_click('" + i + "');"

Note how the double quotes are necessary at both ends of the invariant parts.

answered Mar 23, 2011 at 19:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.