【发布时间】:2011-08-09 17:50:45
【问题描述】:
所以我已经“解决”了我的实际问题,并将问题改为询问“为什么这是个问题?”
我这里有这段代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>iFrame Page Loading</title>
<script type='application/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
<script type='application/javascript'>
$(document).ready(function() {
var $form = $('form');
var $target = $('#target');
// Create an invisible iframe right after the form.
var $iframe = $('<iframe name="_hidden"></iframe>').hide();
// Change this line to the commented version after it to fix all problems:
$target.append($iframe);
// $target.parent().append($iframe);
// Make the form target the iframe.
$form.attr('target', '_hidden');
// Make the form action the 'ajax_load' value.
$form.attr('action', $form.find('.ajax_load').attr('value'));
// On form submit, create an event to replace $target with iframe's
// contents on iframe load.
$form.submit(function() {
$iframe.bind('load', function() {
$target.html($iframe.contents().find('*').html());
// Uncommenting this line fixes Firefox but not Safari - see below
// $target.append($iframe);
$iframe.unbind('load');
});
});
});
</script>
</head>
<body>
<form method='get' action=''>
<input type='hidden' class='ajax_load' value='test.html' />
<input type='submit' value='Load' />
</form>
<div id='target'></div>
</body>
</html>
(应该可以通过将“test.html”更改为其他文件来测试它,只要它是本地文件即可;由于跨域限制,google.com 无法运行)
它完全按照我的意愿去做:首先它在#target 中创建一个不可见的 iframe,然后它更改表单以便它获取一个新的 URL 并以 iframe 为目标。提交时,iframe 会加载抓取的内容。加载时,iframe 中的 html 会替换 #target 中的 html。
问题是浏览器加载 iframe 后,它一直在加载……一些东西。 Firefox 没有说什么,并且愉快地不停地咕咕叫。 Safari 说出了点问题并停止了,我能从中得到的最好信息是 iframe 加载时发生了某种疯狂的递归。这并不理想。
当我将隐藏的 iframe 放在目标之外时,问题就消失了。仅当我确保在加载 html 后再次将 iframe 附加到目标时,它才会在 Firefox 中消失。
所以,我不再有实际问题,但我非常想知道为什么做我正在做的事情是一个问题:从隐藏的 iframe 加载 HTML 并使用它来替换 HTML 内容该 iframe 的父节点。
【问题讨论】:
-
请指定浏览器+版本+操作系统。