简体   繁体   English

未捕获的SyntaxError:意外的令牌}

[英]Uncaught SyntaxError: Unexpected token }

I have a piece of jQuery code which appends an input button to the body and then assigns an onclick function to it. 我有一个jQuery代码,它将一个输入按钮附加到正文,然后为它分配一个onclick函数。 The function that is meant to be called has been defined elsewhere and takes two arguments which are variables that have been defined just before. 要调用的函数已在别处定义,并且接受两个参数,这些参数是之前定义的变量。

This is the code I'm currently using: 这是我目前正在使用的代码:

$("body").append("<input type='submit' value='foo' onclick='foo(\'" + argument1 + "\',\'" + argument2 + "\'/>");

However, when I try to click on the button, I get an error (in Chrome) saying: Uncaught SyntaxError: Unexpected token }. 但是,当我尝试单击按钮时,我收到错误(在Chrome中)说:Uncaught SyntaxError:Unexpected token}。

Can anyone help me? 谁能帮我?

You should assign the click handler using jQuery: 您应该使用jQuery分配单击处理程序:

var input = $('<input type="submit" value="foo" />')
    .click(function() { foo(argument1, argument2); })
    .appendTo(document.body);

Note that this will capture the argument variables by reference. 请注意,这将通过引用捕获参数变量。

你还没有在onclick中关闭foo()函数

Suppose argument1 == '1' and argument2 == '2' , your .append will give 假设argument1 == '1'argument2 == '2' ,你的.append将给出

<input type='submit' value='foo' onclick='foo('1','1'/>

which is obviously not valid HTML. 这显然不是有效的HTML。 To fix it you should use 要修复它你应该使用

.append("<input ... onclick='foo(\"" + argument1 + "\",\"" + argument2 + "\")'/>")

But this is not the right way to use jQuery. 但这不是使用jQuery的正确方法。 See @SLaks's answer for better code. 有关更好的代码,请参阅@ SLaks的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM