document.body.innerHTML = "An error occurred. Please try to login again.<br>";
document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login' onclick='alert(document.getElementById('password').value)'>"
运行此代码然后点击登录按钮后,Chrome JavaScript控制台会返回:
SyntaxError:expected expression,got'}'
我该如何解决?
答案 0 :(得分:3)
您需要更改引号并在javascript代码中转义它们:
document.body.innerHTML = "An error occurred. Please try to login again.<br>";
document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password" id="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login' onclick='alert(document.getElementById(\"password\").value)'>";
至于“为什么浏览器抛出此特定错误?”的原因,这里是问题:
由于代码错误,浏览器实际上会看到以下代码:
(function(event){alert(document.getElementById(
})
正如您所看到的那样 - 在document.getElementById(
之后有一个结束{
,这是您的浏览器对您大吼大叫。
答案 1 :(得分:1)
只是逃避引号
document.body.innerHTML = "An error occurred. Please try to login again.<br>";
document.body.innerHTML += 'Username: <input type="text" name="username"><br>';
document.body.innerHTML += 'Password: <input type="password" name="password" id="password"><br>';
document.body.innerHTML += "<input type='submit' value='Login' onclick='alert(document.getElementById(\"password\").value);return false;' />"
&#13;