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 0
Add a ment  | 

3 Answers 3

Reset to default 5

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.

本文标签: javascriptUncaught SyntaxError Unexpected token Stack Overflow