在您的演示链接中,您的 iframe 已经包含尝试访问$或jQuery在您find("body").append(script);将被计算之前的方式的 javascript。所以这会引发一个错误,因为$还不存在。您要么需要做以下两件事之一:
手动将 jQuery 脚本标签包含在 iframe 源代码的头部。考虑到您的 iframe 源代码中有 jQuery 代码,为什么不这样做呢?
不要有任何脚本试图访问jQuery或$在您的 iframe 的源中,除非引用位于函数或单独的脚本中,这些脚本只有在您插入 jQuery 脚本标签后才会执行。
基本上对于第 2 点,不要直接在 iframe 中使用它:
<script>
/// dolar wont exist yet
$(function(){
})
</script>
而是在您的父代码中执行此操作:
var insertScript = function(src){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
$("#main_iframe").contents().find("body").append(script);
}
$(function() {
insertScript('http://code.jquery.com/jquery-latest.min.js');
// any code in your iframe that relies on jQuery should be
// moved off into this file
insertScript('iframe-js-code-that-requires-jq.js');
});
但是,在 iframe 源中已有 jQuery 脚本标签而不是动态插入它仍然更有意义。