如何在innerHTML(JavaScript)中将对象传递给函数?
如何在innerHTML中将对象传递给函数 以下是一个例子:如何在innerHTML(JavaScript)中将对象传递给函数?,javascript,function,object,innerhtml,Javascript,Function,Object,Innerhtml,如何在innerHTML中将对象传递给函数 以下是一个例子: 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=\"ImageOnLo
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 = html;
}
function ImageOnLoad(coord)
{
if (coord) alert("Success");
else alert("Fail");
}
函数clickme()
{
var-coord={x:5,y:10};
Testimageh(coord);
}
功能测试图像(协调)
{
var html=“”;
document.getElementById(“内容”).innerHTML=html;
}
函数ImageOnLoad(coord)
{
如果(协调)警报(“成功”);
其他警报(“失败”);
}
我怎样才能通过这个物体,coord?这是我目前唯一的另一个方法,是传递coord.x和coord.y,而不是对象
谢谢。按照您现在的实现方式,是的——您正在将HTML创建为字符串,并在该字符串中嵌入JavaScript;你的选择是有限的
哎呀,在
html
var周围使用单引号,这样你就不必逃避一切:(你现在实现它的方式,是的——你将html创建为一个字符串,并在该字符串中嵌入JavaScript;你的选择是有限的
哎呀,在
html
var周围使用单引号,这样就不必转义所有内容:(最简单的方法是创建一个图像,附加事件处理程序,并使用DOM方法插入元素
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);
}
请注意,这与上面的代码有一个区别:它不会删除当前
#content
中的任何元素。如果发生这种情况,则必须单独进行删除。最简单的方法是创建一个映像,附加事件处理程序并使用DOM方法插入元素
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);
}
请注意,这与您上面的代码有一个区别:它不会删除当前#content
中的任何元素。如果发生这种情况,您必须单独进行删除。您可以使用而不是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);
您可以使用而不是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);