【问题标题】:"Unexpected call to method or property access." in IE with appendChild()“对方法或属性访问的意外调用。”在 IE 中使用 appendChild()
【发布时间】:2011-07-07 23:52:39
【问题描述】:
function fload(){
  f = document.createElement('iframe');
  f.setAttribute('id','iframe');
  f.setAttribute('src','http://www.wtsp.com/news/article/199268/8/man-falls-behind-on-payments-mortgage-company-has-home-trashed');
  f.setAttribute('frameborder','0');
  document.getElementById('content').appendChild(f);
}

我正在尝试在其他所有内容加载后加载 iframe。以上是代码。在 IE9 中,控制台显示“SCRIPT65535:意外调用方法或属性访问”。用 appendChild() 指向行。

另外,是否可以异步加载 iframe?

【问题讨论】:

  • 您应该使用varf 限定为该函数。另外,您确定在运行此代码时存在具有content id 的元素吗?
  • 它在 IE9 中工作,如下 jsfiddle 所示:jsfiddle.net/jfriend00/GVNSf。我认为这意味着 document.getElementById('content') 一定不能在您的实际页面中工作。你什么时候打电话给fload。是在页面加载之后吗?如果你调用它太早,那么内容对象可能还不存在。
  • 框架将按原样异步加载。
  • 我发现我在IE7兼容模式下运行IE,我将它切换回默认并且不再出现错误。我添加了“var”以防万一。

标签: javascript internet-explorer iframe


【解决方案1】:

正如评论者所说,id 为 content 的元素可能还不存在。另外,你不需要使用 setAttribute,直接设置 DOM 属性即可:

function fload(){
  var f;
  var el = document.getElementById('content');

  if (el && el.appendChild) {
    f = document.createElement('iframe');
    f.id = 'iframe';
    f.src = 'http://...';
    f.frameborder = '0';
    el.appendChild(f);
  }
}

在您确信元素存在之前,不应调用上述函数,例如在加载事件或类似事件之后。

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多