最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onclick="doSomething([object Object])" Uncaught SyntaxError: Unexpected identifier - Stack Overfl

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Aug 1, 2012 at 5:50 melomelo 932 gold badges2 silver badges5 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 13

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.

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

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

The answer by Li0liQ is quite Ok. When you clicking on that link you can find doSomething[object Object]

This is only object required .You are not writing the params into document. Casting Problem.

Ran into same issue. Reason for the issue: params is converted to string 'object Object' when html is rendered.

The problem can be sorted out in two ways:

Approach 1: add a click handler to the js code. Refer add click handler

Approach 2: Say I want to pass a JSON object named 'params' to the onclick function. As I need a very few attributes of the 'params' object, instead of adding a new handler as in 1st approach, I would rather just pass those specific parameters as below:

'<a href="#" onclick="doSomething(\'' + params['attribute1'] + '\'\, \'' +params['attribute2'] + '\'\)">aaa</a>'

<button class="btn btn-primary" onclick='setInputForUpdate(${JSON.stringify(data)})' data-bs-toggle="modal"

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论