我正在尝试使用JavaScript创建<iframe>,然后将<script>元素附加到<iframe>,我想在<iframe> d文档的上下文中运行.
不幸的是,我似乎做错了 - 我的JavaScript似乎成功执行,但<script>的上下文是父页面,而不是<iframe> d文档.当浏览器请求iframe_test.js时,我在Firebug的"Net"选项卡中也会收到301错误,但它会再次请求它(不知道为什么?)成功.
这是我正在使用的代码(现场演示http://onespot.wsj.com/static/iframe_test.html):
iframe_test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><iframe> test</title>
</head>
<body>
<div id="bucket"></div>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#bucket').append('<iframe id="test"></iframe>');
setTimeout(function() {
var iframe_body = $('#test').contents().find('body');
iframe_body.append('<scr' + 'ipt type="text/javascript" src="http://onespot.wsj.com/static/iframe_test.js"></scr' + 'ipt>');
}, 100);
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
iframe_test.js
$(function() {
var test = '<p>Shouldn\'t this be inside the <iframe>?</p>';
$('body').append(test);
});
Run Code Online (Sandbox Code Playgroud)
一件似乎不寻常的事情是iframe_test.js中的代码甚至可以工作; …