<\/script>')

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 on <a> on the page, it throws "Uncaught SyntaxError: Unexpected identifier". I can not understand.

+4
source share
4 answers

The reason is that when you use string concatenation, params is called into a string, as a result you get something like [object Object] in brackets.

You better put the parameters like var params = '{a:1,b:2}'; .

Upd.
As suggested in the comments, another viable approach uses JSON.stringify :

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

Please note that JSON.stringify may not be supported by older browsers, and you will need to include additional libraries to make them work.

+10
source

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

+1
source

In your case, str looks like this: <a href="#" onclick="doSomething([object Object])">aaaa</a>

As you can see, this is not what you want.

0
source

Li0liQ's answer is pretty good. When you click on this link, you can find doSomething[object Object]

This is just the required object. You do not write parameters to document . Casting problem.

0
source

All Articles