Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick="doSomething([object Object])" Uncaught SyntaxError: Unexpected identifier

var params = {a:1,b:2}; var str = '<a href="#" onclick="doSomething('+params+')">aaaa</a>'; document.write(str);

when I click the <a> on the page,it throws "Uncaught SyntaxError: Unexpected identifier".I can't understand.

like image 973
melo Avatar asked Aug 01 '12 05:08

melo


2 Answers

The reason is that when you use string concatenation, params is casted to string, as result you get something like [object Object] in parenthesis.

You should better put params as var params = '{a:1,b:2}';.

Upd.
As suggested in comments, another viable approach is using JSON.stringify:

var params = {a:1,b:2};
var str = '<a href="#" onclick="doSomething('
    + JSON.stringify(params)
    + ')">aaaa</a>';
document.write(str);

Please, pay attention that JSON.stringify may not be supported by older browsers and you'll need to include additional libraries to make them work.

like image 151
Li0liQ Avatar answered Oct 20 '22 16:10

Li0liQ


[object Object] is the string representation of any JavaScript object. In your scenario you have params concatenated with a string, which will cast any variable type to a string.

like image 1
Matt Lo Avatar answered Oct 20 '22 16:10

Matt Lo