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.
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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With