【问题标题】:How can I pass an object to a function in innerHTML (JavaScript)?如何将对象传递给 innerHTML (JavaScript) 中的函数?
【发布时间】:2011-12-06 06:58:58
【问题描述】:

如何将对象传递给 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,而不是对象。

谢谢。

【问题讨论】:

    标签: javascript function object innerhtml


    【解决方案1】:

    最简单的方法是创建图像、附加事件处理程序并使用 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 中的任何元素。如果发生这种情况,您将不得不单独进行删除。

    【讨论】:

      【解决方案2】:

      您可以使用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);
      

      【讨论】:

        【解决方案3】:

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

        天哪,在html var 周围使用单引号,这样您就不必转义所有内容:(

        【讨论】:

          猜你喜欢
          • 2011-12-07
          • 1970-01-01
          • 2014-09-10
          • 1970-01-01
          • 1970-01-01
          • 2010-11-19
          • 2020-03-30
          • 1970-01-01
          相关资源
          最近更新 更多