开发者

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. 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 butto开发者_如何学Cn, I get an error (in Chrome) saying: Uncaught SyntaxError: Unexpected token }.

Can anyone help me?


You 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜