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