Using innerHTML techniques, the following works just fine on all 4 common browsers (IE, FF, Safari and Opera):
container.innerHTML += "<div onclick='someFunction(even
t,1,2,3)'>
hi</div>";
In certain scenarios I would prefer a more DOM oriented approach, in which case the equivalent would be:
var d = document.createElement("DI
V");
d.setAttribute ("onclick", "someFunction(event,1,2,3)
");
d.innerHTML = "hi";
container.appendChild(d);
However, this doesn't seem to work on all browsers. For instance IE doesn't seem to want a string for the parameter. I tried writing a function to help:
function setHandler (obj, theEvent, funcName)
{
var paramString = '';
for(var i=3; i<arguments.length; i++)
paramString += ",'" + arguments[i] + "'";
if (document.all)
obj.setAttribute(theEvent,
new Function(funcName +
"(window.event" + paramString + ")"));
else
obj.setAttribute(theEvent,
funcName + "(event" + paramString + ")");
}
Then I would do:
setHandler (d, "onclick", "someFunction", 1, 2, 3);
Now I am told that this won't work on Safari. Is this true (I don't have a mac handy)?
I am also told that the "new Function" creates a closure, which might have some side effects. (I have to admit I don't really understand closures well)
Is there a better way to do this?
I really want it to create the element that is exactly the same as if I had done it the innerHTML way. Hopefully that is not too much to ask..... :)
BTW, I could live without the "event" parameter being passed to the function, as I almost never use it, but I do need to set the other parameters on a case by case basis.
Start Free Trial