How can I pass an object to a function in innerHTML (JavaScript)?
How can I pass an object to a function in innerHTML?
Here is an example:
function clickme()
{
var coord = {x:5, y:10};
testimageih(coord);
}
function testimageih(coord)
{
var html = "<img id=\"sam1\" border=\"0\" name=\"sam1\" src=\"sample.gif\" " +
"onLoad=\"ImageOnLoad(" + coord + ");\"></img>";
document.getElementById("content").innerHTML = htm开发者_开发问答l;
}
function ImageOnLoad(coord)
{
if (coord) alert("Success");
else alert("Fail");
}
How can I pass this object, coord? It's my only other recourse, at the moment, is passing coord.x and coord.y, instead of the object.
Thank you.
The simplest way is to create an image, attach the event handler and insert the element using DOM methods.
function testimageih(coord)
{
var img = document.createElement('img');
img.id = 'sam1';
img.border = 0;
img.name = 'sam1';
img.src = 'sample.gif';
img.onload = function() {
ImageOnLoad(coord);
};
document.getElementById('content').appendChild(img);
}
Note that this has one difference to the code you have above: it doesn't remove any elements currently in #content
. If that will happen, you will have to do the removal separately.
You could use document.createElement
instead of innerHTML
.
// Create the element
var element = document.createElement('img');
element.setAttribute('border', 0);
element.setAttribute('name', 'sam1');
element.setAttribute('src', 'sample.gif');
// Attach onLoad handler to it (passing it the object)
element.onload = function() { ImageOnLoad(coord) };
// Replace the contents of your... div?
var content = document.getElementById("content")
content.innerHTML = '';
content.appendChild(element);
The way you are implementing it now, yes--you're creating HTML as a string, and embedding JavaScript within that string; your options are limited.
And geez, use single-quotes around the html
var so you don't have to escape everything :(
精彩评论