Javascript Illegal Token Error

风流意气都作罢 提交于 2019-12-21 22:14:45

问题


Forgive me if this is a simple problem but I can't seem to find why this code:

function create_content(c)
        {
            var html = "<div id='header'>"+c+"</div>";
            if(c == "links")
            {
                var ul = "<ul><li><a href='http://www.mylink.com'>My Link 1</a></li>
<li><a href='http://www.mylink2.co.uk'>My Link 2</a></li></ul>";
                html = html + ul;
            }
            return(html);
        }

Is giving me this error in Chrome (win):

Uncaught SyntaxError: Unexpected token ILLEGAL

On the line that starts with "var ul = "

Any advice would help thanks!


回答1:


You are inserting a line break in your ul string, between the closing </li> and the opening <li>. JavaScript string literals cannot span multiple lines like this by themselves, unless you

  • Trail a \ at each line but the last (as Ivo Wetzel says):

    var ul = "<ul><li><a href='http://www.mylink.com'>My Link 1</a></li>\
    <li><a href='http://www.mylink2.co.uk'>My Link 2</a></li></ul>";
    
  • Break them and concatenate the parts, like this:

    var ul = "<ul><li><a href='http://www.mylink.com'>My Link 1</a></li>";
    ul += "<li><a href='http://www.mylink2.co.uk'>My Link 2</a></li></ul>";
    

    (To keep the newline there you would place a \n somewhere, but in HTML it won't matter.)




回答2:


I found I needed to escape the forward slashes in my closing tags. ie;

<\/script>

or

<\/form>

Then the "Uncaught SyntaxError: Unexpected token ILLEGAL" Error went away and my code processed fine.



来源:https://stackoverflow.com/questions/4635487/javascript-illegal-token-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!