【问题标题】:Web development : how to make button click event download a file using html + jQuery?Web 开发:如何使用 html + jQuery 使按钮单击事件下载文件?
【发布时间】:2023-03-09 00:57:01
【问题描述】:

我需要创建一个 html 脚本来创建联系人表并使用 jQuery。我正在尝试下载此 html 页面并将其转换为 excel 文件。

谁能帮帮我??

我有这个html文件

contact.html

<div id="dv">
  <table id="tblExport" style="border:1px solid black; ">
    <thead>
      <tr>
        <th>#</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style='background-color:red;'>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>
</div>
<div>
  <button id="btnExport">Export to excel</button>
</div>

</div>

那么如何使用jQuery让按钮下载这个表格并进行转换 到excel表格??

【问题讨论】:

    标签: jquery html jquery-click-event


    【解决方案1】:

    使用 data:application 属性:

    $("#Export").click(function (e) {
        window.open('data:application/vnd.ms-excel,' + $('#dv').html());
        e.preventDefault();
    });
    

    用 Excel 打开下载的文件。

    http://jsfiddle.net/eozwh49u/

    【讨论】:

    • 我正在尝试使用您的代码,但它没有下载任何内容,所以我做错了什么?
    • 尝试使用 chrome 或 firefox 下载文件
    • 实际上我使用的是 Firefox 和 chrome,但现在当我点击按钮时会发生操作
    • btnExport 的OP html 相比,此代码的#Export 按钮选择器不正确
    【解决方案2】:

    您应该使用 jquery on 事件而不是 click。因为如果您通过 ajax 加载表单,那么 click 将不起作用。然后您可以在您的div 上使用简单的html 函数来获取html 内容并将其传递给excel

    $("body").on("click", "#btnExport", function () {
        window.open('data:application/vnd.ms-excel,' + $('#dv').html());
    });
    

    【讨论】:

      【解决方案3】:

      只需在按钮上放置一个点击处理程序,然后导出 div

      $("#btnExport").on("click", function() {
          window.open('data:application/vnd.ms-excel,' + $('#dv').html());
      });
      

      现在,如果您愿意,您可以从代码中触发:

      $("#btnExport").trigger('click');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多