admin管理员组文章数量:1295743
I have a piece of jQuery code which appends an input button to the body and then assigns an onclick function to it. 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 }.
Can anyone help me?
I have a piece of jQuery code which appends an input button to the body and then assigns an onclick function to it. 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 }.
Can anyone help me?
Share Improve this question edited Aug 29, 2010 at 21:03 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked Aug 29, 2010 at 20:50 DLiKSDLiKS 1,5964 gold badges21 silver badges32 bronze badges 03 Answers
Reset to default 5You should assign the click handler using 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.
You haven't closed the foo() function in the onclick
Suppose argument1 == '1'
and argument2 == '2'
, your .append
will give
<input type='submit' value='foo' onclick='foo('1','1'/>
which is obviously not valid HTML. To fix it you should use
.append("<input ... onclick='foo(\"" + argument1 + "\",\"" + argument2 + "\")'/>")
But this is not the right way to use jQuery. See @SLaks's answer for better code.
本文标签: javascriptUncaught SyntaxError Unexpected token Stack Overflow
版权声明:本文标题:javascript - Uncaught SyntaxError: Unexpected token } - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741620888a2388803.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论