单击href时阻止打开新页面

时间:2018-02-05 16:23:00

标签: javascript html excel

我的目标是将html表下载到excel文件中,该文件会在单击按钮时自动下载。该按钮调用函数fnExportExcel()

我使用以下代码将html表导出为ex​​cel文件:

function fnExportExcel() {
    var dt = new Date();
    var day = dt.getDate();
    var month = dt.getMonth() + 1;
    var year = dt.getFullYear();
    var hour = dt.getHours();
    var mins = dt.getMinutes();
    var postfix = month + "." + day + "." + year + "_" + hour + "." + mins;
    //creating a temporary HTML link element (they support setting file names)
    var a = document.createElement('a');
    //getting data from our div that contains the HTML table
    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('datatable');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');
    a.href = data_type + ', ' + table_html;
    //setting the file name
    a.download = 'MachineReport_' + postfix + '.xls';
    //triggering the function
    a.click();
    //just in case, prevent default behaviour
    e.preventDefault();
}

e.preventDefault()无效,但正在下载excel文件。正在加载新页面并且未找到。还有其他方法可以防止这种情况发生吗?

2 个答案:

答案 0 :(得分:2)

调用e.preventDefault()表明e已经是回调函数中的参数。

您需要为click创建一个事件侦听器,以便从e回调中获取event参数。

let anchorTag = document.querySelector('a')

anchorTag.addEventListener('click', e => { //notice the passing of `e` (this stands for event)
  e.preventDefault() //preventing the event here
  //logic goes here
})
<a href="/my/url">click here for nothing to happen</a>

答案 1 :(得分:0)

您可以查看this fiddle

let link = document.getElementById("myLink"); //Here write the ID of your <a> element.
link.addEventListener("mouseover", link.showHref = function(e) {
  let target = e.target || this;
  if (link.mouseDown)
    link.mouseDown = false;
  else
    target.href = target._href || target.href;
});
link.addEventListener("mousemove", link.showHref);
link.addEventListener("mouseup", link.showHrefForced = function(e) {
    link.mouseDown = false;
});
link.addEventListener("touchend", link.showHrefForced);
link.addEventListener("mousedown", link.cancelHref = function(e) {
  let target = e.target || this;
  if (target.href !== "javascript:void(0)")
    target._href = target.href;
  target.href = "javascript:void(0)";
  link.mouseDown = true;
});
link.addEventListener("touchstart", link.cancelHref);
link.addEventListener("click", function(e) {
    e.preventDefault();
  link.showHref(e);
  let target = e.target || this;
    let url = target._href || target.href;
  let newLink = document.createElement("a");
  newLink.download = link.name;
  newLink.href = url;
  newLink.click();
});

解决方案主要包括以编程方式禁用<a>元素的单击,避免浏览页面,而创建隐藏的<a>元素(未添加到父元素)并执行其单击静默下载URI。