javascript: pass an object as the argument to a onclick function inside string
The above example does not work because the output of obj
to text is [Object object]
, so essentially, you are calling someListener([Object object])
.
While you have the instance of the element in o
, bind to it's click using javascript:
function myfunction(obj,parentobj){
var o=document.createElement("div");
o.innerHTML='<input type="button" />';
o.onClick = function () {
someListener(obj)
}
parentobj.appendChild(o.firstChild);
}
I have created a working fiddle for you here: JSFiddle
function myfunction(obj,parentobj){
var o=document.createElement("div");
o.innerHTML="<input type='button' onclick='somelistener("+JSON.stringify(obj)+")'/>";
parentobj.appendChild(o.firstChild);
}
// my similar problem, function a was called in a jsonArray loop in the dataTable initiation
function a(data, type, obj) {
var str = "";
str += "<span class='button-group'>";
str +="<a onclick='chooseData1("+JSON.stringify(obj)+")'>[选择]</a>";
str += "</span>";
return str;
}
function chooseData1(data){
console.log(data);
}