为什么我得到意外令牌非法在javascript

Why am I getting Unexpected token illegal in javascript?

本文关键字:非法 javascript 令牌 意外 为什么      更新时间:2023-09-26

为什么我在这个脚本中得到错误"意外令牌非法" ?该脚本应该检索所有cookie并在表中显示它们的名称和值。错误发生在有开始表标记的那行。

document.getElementById("showCookies").onclick = function(){
        var columnRight = document.getElementById('columnRight');
        var cookies = document.cookie;
        var cookiesContent = '<h1>Existing Cookies</h1>';
        console.log(cookies);
        cookies = cookies.split(";");
        if(cookies.length > 0){
            cookiesContent += '<table width="30%" cellspacing="1" cellpadding="10" border="0">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Value</th>
                </tr>
            </thead>
            <tbody>
                ';
            for(var i = 0; i < cookies.length; i++){
                cookieAtts = cookies[i].split('=');
                cookiesContent += "<tr><td>" + cookieAtts[0] + "</td><td>" + cookieAtts[1] + "</td></tr>";
            }
            cookiesContent += "</tbody></table>";
        }
        columnRight.innerHTML = cookiesContent;
        return false;
    }

使用字符串连接来定义长字符串:

cookiesContent += '<table width="30%" cellspacing="1" cellpadding="10" border="0">' +
            '<thead>'+
                '<tr>' +
                    '<th>Name</th>'+
                    '<th>Value</th>'+
                '</tr>'+
            '</thead>'+
            '<tbody>';

这是因为你不能在JavaScript中有多行字符串没有反斜杠:

cookiesContent += '<table width="30%" cellspacing="1" cellpadding="10" border="0"> '
            <thead> '
                <tr> '
                    <th>Name</th> '
                    <th>Value</th> '
                </tr> '
            </thead> '
            <tbody> '
                ';

您的字符串中有<thead...换行,这是不允许的

连接此:

cookiesContent += '<table width="30%" cellspacing="1" cellpadding="10" border="0">' +
        '<thead> ' +
            '<tr> ' +
                '<th>Name</th>' +
                '<th>Value</th>' +
            '</tr>' +
        '</thead>' +
        '<tbody>';

或者在同一行:

cookiesContent += '<table width="30%" cellspacing="1" cellpadding="10" border="0"><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>';