未捕获的SyntaxError:意外的标识符错误

时间:2014-01-21 14:07:41

标签: javascript

每当我尝试点击下面的链接时,我都会在Chrome开发者工具控制台中收到(未捕获的SyntaxError:意外的标识符错误)。我在代码中看不到任何错误,所以有人可以检查一下并告诉我这里缺少什么吗?

<a href="javascript:warningMsg('Are you sure you want to delete this User? This step can't be undone!','/invoicing/users/','2','delete-user')">Delete User</a>

下面是warningMsg函数,遗憾的是它甚至没有被调用,但包含它的.js文件包含在html页面中,上面有链接:

function warningMsg(warningMsgContent, url, id, actionType){
 alert(url+actionType+"?id="+id);
 window.location.assign(url+actionType+"/?id="+id);
}

注意:我试图逃避'不能通过做它不能但我得到同样的错误

感谢您的时间和努力

5 个答案:

答案 0 :(得分:3)

这是因为“不能”这个词中的' - 它会导致您的报价不匹配。

'Are you sure you want to delete this User? This step can't be undone!'
^                                                        ^            ^

要解决此问题,您需要使用反斜杠转义“{not}”中的'

'Are you sure you want to delete this User? This step can\'t be undone!'

答案 1 :(得分:1)

can't中有一个未转义的单引号。它应该是can\t

<a href="javascript:warningMsg('Are you sure you want to delete this User? This step can\'t be undone!','/invoicing/users/','2','delete-user')">Delete User</a>

但是,永远不应该使用内联js(html中的javascript)(除非出于快速测试目的)。阅读其中一些结果: Why is inline js bad?

相反,请使用javascript附加javascript!

<a id="delete-user">Delete User</a>

<强> JavaScript的:

var d = document.getElementById('delete-user');
d.addEventListener('click', function() {
  warningMsg(
    "Are you sure you want to delete this User? This step can't be undone!",
    '/invoicing/users/',
    '2',
    'delete-user'
  );
});

<强> Here's a live demo you can mess with.

答案 2 :(得分:0)

尝试This step can\'t be undone!

而不是This step can't be undone!

答案 3 :(得分:0)

window.location.assign(url+actionType+"/?id="+id);中,您将得到类似于以下内容的结果:

/invoicing/users/?id=2

由于这个原因:url+actionType+"/?id="+id

当然,这是除了其他人提到的报价转义问题之外的其他问题。

答案 4 :(得分:0)

取代:

<a href="javascript:warningMsg('Are you sure you want to delete this User? This step can't be undone!','/invoicing/users/','2','delete-user')">Delete User</a>

为:

<a href="javascript:warningMsg('Are you sure you want to delete this User? This step can\'t be undone!','/invoicing/users/','2','delete-user')">Delete User</a>

(需要逃避单词中的'不能)

无论如何,我建议您使用事件处理程序而不是内联代码(onclick = ...):

HTML:

<a id="btn_delete" href="#">Delete user</a>

的javascript:

document.getElementById('btn_delete').addEventListener('click', function() {
    warningMsg('Are you sure you want to delete this User? This step can\'t be undone!','/invoicing/users/','2','delete-user');
});
希望有所帮助。