Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Illegal Token Error

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!

like image 210
Doug Molineux Avatar asked Dec 01 '25 08:12

Doug Molineux


1 Answers

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

like image 114
BoltClock Avatar answered Dec 03 '25 21:12

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!