开发者

Passing a variable to another function in Javascript

I asked a question a while back about how to get the current variable in a loop and I got the sol开发者_开发知识库ution :

    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?


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).


Try this:

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


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 + "');"...}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜