【问题标题】:How to run dynamically loaded js file in iframe?如何在 iframe 中运行动态加载的 js 文件?
【发布时间】:2010-03-07 03:39:53
【问题描述】:

我有以下几点:

$(document).ready(function() {

  var myIframe = document.getElementById('myIframe');
  var element = myIframe.contentDocument.createElement('script');  
  element.setAttribute('src', '/javascripts/library/jquery/jquery.min.js');  
  myIframe.contentWindow.document.getElementsByTagName('head')[0].appendChild(element);

  $('#myIframe', top.document).load(function() {
    alert('iframe has loaded');

    var element = document.getElementById('myIframe').contentDocument.createElement('script');  
    element.setAttribute('src', '/javascripts/stuff.js');  
    myIframe.contentWindow.document.getElementsByTagName('body')[0].appendChild(element);  
  });

});

我收到“iframe 已加载”的警报。

stuff.js 包含

$('body').css('backgroundColor', 'yellow');

所以,我希望 iframe 的背景颜色会在 iframe 加载后变为黄色......但没有任何反应。我什至尝试在 $(document).ready 块中包含 stuff.js 中的内容,但结果相同。

如果我选择所有并查看 iframe 的源代码,我会看到 jquery.min.js 和 stuff.js 在 iframe 的 .如果我将此源输出放入单独的 html 文件并运行该文件,则文档的背景颜色会按预期更改。

加载 iframe 后,如何让我在 stuff.js 中的 javascript 在 iframe 中运行?

【问题讨论】:

  • 您是否收到任何脚本错误?你在 stuff.js 中尝试过alert 吗?你检查过 Firebug 吗?
  • 没有脚本错误,也没有警报。从商店回来后,我会和 Firebug 一起四处窥探。
  • 我用 Firebug 看它时没有发现任何奇怪的地方。

标签: jquery iframe


【解决方案1】:

你也可以用更 jQuery 的方式来做。

$('<script/>', {
    src: '/path/to/javascript.js',
    type: 'text/javascript'
}).appendTo($('#iframe').contents().find('body'));

【讨论】:

    【解决方案2】:

    是的,我想通了!

    原来它不起作用,因为我已将 myIframe.contentDocument.designMode 设置为“on”。评论出来使它工作。希望在 stuff.js 加载后我可以打开它,一切都会好起来的。

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多