我目前在 AJAX 上传表单中使用 iframe,我的问题是一旦文件上传到 iframe 它就会将数据附加到 div,所以我可以肯定地说我可以在加载完成后删除 iframe ?
我的js是
$("#formsubmit").click(function (event) {
event.preventDefault();
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
$("body").append(iframe);
var form = $('#theuploadform');
form.attr("action", "uploader.php");
form.attr("method", "post");
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#userfile').val());
form.submit();
$("#postiframe").load(function () {
iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
$("#textarea").html(iframeContents);
$("#postiframe").remove(); // i thought this would do it but it doesn't
});
return false;
});
即使我有 event.preventDefault();如果我删除底部的 return false,它仍然会提交表单(刷新到新页面)。
我的 html 是:
<div id="uploadform">
<form id="theuploadform" action="">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
</div>
<div id="textarea"></div>
总结一下我的问题:
- 是否可以在上传后将 iframe 复制到“textarea”后删除
- 如果是这样 $("#postiframe").remove 不起作用
- 有谁知道为什么当我删除 return false 时,它会重新加载页面而不是使用 event.preventDefault();一开始
提前谢谢你。
最佳答案
你的 <iframe>
在页面加载后通过 JavaScript 附加到窗口文档,使用:
$(document).find('#postiframe').remove();
这将遍历 DOM 并找到您新指定的 <iframe>
,然后按预期从 DOM 中动态删除它。
尝试 <input type="button" />
处理表格而不是 <input type="submit" />
, 如果你还想处理 <input type="submit" />
表单提交依旧,试试:
$('#theuploadform').submit(function(event){
event.preventDefault();
});
取而代之的是函数,这将允许 jQuery 阻止整个表单及其所有子元素的默认行为。
关于javascript - 上传后是否可以删除iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18385042/