【问题标题】:how to correctly stop the transport inside an iframe如何正确停止 iframe 内的传输
【发布时间】:2012-05-04 02:56:25
【问题描述】:

当用户单击“取消”按钮时,我试图阻止文件上传。为此,我正在考虑停止 iframe 内的传输。问题是能够正确编码。以下是我想要实现的代码,但我在这里收到此错误:

$('.upload_target').contentWindow is undefined

首先如何解决这个错误,其次如何正确编写下面的代码,以便当单击“取消”按钮时,它会停止 iframe 内的传输?

下面是开始上传文件的 startImageUpload() 函数。在该函数中是处理单击“取消”按钮的函数;

function startImageUpload(imageuploadform){


              $(".imageCancel").click(function() {
              $('.upload_target').get(0).contentwindow

              if ($('.upload_target').contentWindow.document.execCommand)
    { // IE browsers
       $('.upload_target').contentWindow.document.execCommand('Stop');
    }
else
    { // other browsers
        $('.upload_target').contentWindow.stop();
    }


          return stopImageUpload();

    });

      return true;
}

以下是包含 iframe 的表单代码:

 var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return startImageUpload(this);' class='imageuploadform' >" + 
    "Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" + 
    "<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" + 
    "</p><p class='imagef1_cancel' align='center'><label>" + 
    "<input type='button' name='imageCancel' class='imageCancel' value='Cancel' /></label></p>" + 
    "<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>"); 

【问题讨论】:

  • 为什么不简单地使用 jquery 表单插件呢?它会根据浏览器支持自动使用 XHR 上传或 iframe。

标签: javascript jquery


【解决方案1】:

$('.upload_target') 将返回一个 jQuery 对象,其中包含该类的所有元素,因此 contentWindow 属性将不存在

$(.upload_target:eq(0)').get() 将返回(第一个但假设只有一个)元素本身,然后 contentWindow 应该存在

$(.upload_target')[0],如果您针对的是单个元素,但 ID 会更高效

【讨论】:

  • 怎么样:例如$('.upload_target').get(0).contentWindow.document.execCommand),可以吗?
  • 是的,应该这样做,而且 [0] 更快,老实说,不是 100% 确定 execCommand 访问权限,如果它失败了开始一个新问题,我相信有人会知道。
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 2021-06-11
相关资源
最近更新 更多