问题描述
var params = {a:1,b:2};var str = '<a href="#" onclick="doSomething('+params+')">aaaa</a>';document.write(str);
当我点击页面上的 时,它抛出Uncaught SyntaxError: Unexpected identifier".我无法理解.
when I click the <a>
on the page,it throws "Uncaught SyntaxError: Unexpected identifier".I can't understand.
推荐答案
原因是当你使用字符串连接时,params
被强制转换为字符串,结果你得到类似 [object Object]
括号内.
The reason is that when you use string concatenation, params
is casted to string, as result you get something like [object Object]
in parenthesis.
你最好把参数设为 var params = '{a:1,b:2}';
.
更新.
正如评论中所建议的,另一种可行的方法是使用 JSON.stringify
:
var params = {a:1,b:2};
var str = '<a href="#" onclick="doSomething('
+ JSON.stringify(params)
+ ')">aaaa</a>';
document.write(str);
请注意,旧版浏览器可能不支持 JSON.stringify
,您需要包含 附加库 使它们工作.
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.
这篇关于onclick="doSomething([object Object])";未捕获的语法错误:意外的标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!