2011-10-12 46 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

相關問題