![](/img/trans.png)
[英]How can I pass my dynamically-generated variable to the function inside the innerHTML of a javascript function?
[英]How can I pass an object to a function in innerHTML (JavaScript)?
如何將對象傳遞給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=\"ImageOnLoad(" + coord + ");\"></img>";
document.getElementById("content").innerHTML = html;
}
function ImageOnLoad(coord)
{
if (coord) alert("Success");
else alert("Fail");
}
我如何傳遞這個對象,協調? 目前,這是我唯一的其他方法,是傳遞coord.x和coord.y而不是傳遞對象。
謝謝。
最簡單的方法是創建圖像,附加事件處理程序並使用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
當前的任何元素。 如果發生這種情況,則必須單獨進行清除。
是的,現在的實現方式是-您正在將HTML創建為字符串,並將JavaScript嵌入該字符串中; 您的選擇是有限的。
和geez,在html
var周圍使用單引號,這樣就不必轉義所有內容了:(
您可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.