Search code examples
javascriptonclicksyntax-error

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


Solution

  • 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.