js模拟a标签实现下载附件

js模拟a标签实现下载附件

  // js模拟a标签,直接下载
 function down(filePath,fileName,fileOldName) {
      var $form = $('<form method="GET"><a id="downFile"></a></form>');
      $form.appendTo($('body'));
      $("#downFile").attr('href','{ctx}/'+filePath+'/'+fileName);
      $("#downFile").attr('download',fileOldName);
      $("#downFile")[0].click();
  }

注意点击事件: $("#downFile")[0].click();

用这个方法可以直接模拟点击href的效果,实现下载。
因为a标签的href属性是在他dom中的0里面,需要点击那个0才能实现,而数字型的属性名不能用“.”来获取,故写成[0]。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41377835/article/details/94457991