2011-10-12 44 views
0

如何将对象传递给innerHTML中的函数?如何将对象传递给innerHTML(JavaScript)中的函数?

下面是一个例子:

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"); 
} 

如何传递这个对象,坐标?这是我唯一的另一种追求,目前正在传递coord.x和coord.y,而不是对象。

谢谢。

回答

1

ÿ你可以使用document.createElement而不是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); 
+0

谢谢你的帮助。 – user717236

1

您现在正在实现它的方式,是的 - 您将HTML创建为字符串,并在该字符串中嵌入JavaScript;你的选择是有限的。

而且吉兹,周围使用html VAR单引号,所以你不必什么都逃不过:(

+0

感谢您的帮助。 – user717236

4

最简单的方法是创建一个图像,附加的事件处理程序,插入使用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任何元素如果这会发生,你将不得不单独做去除

+0

谢谢你的帮助。 – user717236

相关问题