Javascript创建iframe设置内容,然后从一个函数返回

时间:2019-11-01 03:27:48

标签: javascript

我需要动态创建一个iframe,设置其html,然后将其作为函数返回,以便以后可以使用newAdUnit()进行调用。现在,它返回[object HTMLIFrameElement]。我正在尝试从一种功能中找到一种方法来完成所有这些工作。原因是我正在设置需要动态加载的广告。一个函数可以使我的代码更简洁,因为我可以用多种不同的方式来调用它。有什么想法吗?

<script>
function newAdUnit(size) {
    var iframe = document.createElement('iframe');
    iframe.onload = function() {
        iframe = iframe.contentWindow.document;
        var html = '<body>This is a test</body>';
        iframe.open();
        iframe.write(html);
        iframe.close();
    };
    return iframe;
}
</script>
<div id="test">
<script>document.getElementById("test").innerHTML = newAdUnit()</script>
</div>

2 个答案:

答案 0 :(得分:0)

如果对当前操作使用 JQuery ,它将非常容易。下面的代码显示了如何

<html>
  <head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    function newAdUnit(obj) {
        var iframe = document.createElement('iframe');
        iframe.onload = function() {
            iframe = iframe.contentWindow.document;
            var html = '<body>This is a test</body>';
            iframe.open();
            iframe.write(html);
            iframe.close();
        };
        $(obj).append(iframe);
    }

    newAdUnit($('#test'));
  });
  </script>
  </head>
  <body>
    <div id="test">

    </div>
  </body>
</html>

答案 1 :(得分:0)

仅当要添加的内容是HTML字符串时,才应使用.innerHTML。但是,根据您的情况,您有一个HTMLIFrameElement对象,因此,在这种情况下不能使用.innerHTML。当前,Javascript正在对.toString()返回的元素对象上进行隐式调用newAdUnit(),结果是[object HTMLIFrameElement]

相反,当您要将节点元素添加到另一个元素时,可以像这样使用.appendChild()

<div id="test"></div>

<script>
  function newAdUnit(size) {
    var iframe = document.createElement('iframe');
    iframe.onload = function() {
      iframe = iframe.contentWindow.document;
      var html = '<body>This is a test. The size is ' + size + '</body>';
      iframe.open();
      iframe.write(html);
      iframe.close();
    };
    return iframe;
  }

  document.getElementById("test").appendChild(newAdUnit(10));
</script>