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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The reason is that when you use string concatenation,
paramsis 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:Please, pay attention that
JSON.stringifymay not be supported by older browsers and you’ll need to include additional libraries to make them work.