Programmatical click on -tag not working in Firefox

前端 未结 5 608
醉话见心
醉话见心 2020-12-02 17:57

I have a problem with the click()-function from jquery. I create a -element with document.createElement(\'a\') and want call

相关标签:
5条回答
  • 2020-12-02 18:39

    Add the element to the DOM before triggering the click:

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

    This worked for me in all the major browsers

    0 讨论(0)
  • 2020-12-02 18:41

    You can use jquery for creating the element. It will work on both the browsers

    $(document).on('click', '#test', function (event) {
        var link = $("<a/>", {
            "download": "test.xls",
            "href": "data:application/vnd.ms-excel;utf-8,test"
        });
        $("#test").append(link);
        link.get(0).click();
    });
    

    Fiddle

    0 讨论(0)
  • 2020-12-02 18:44

    In Firefox, you can explicitly add the created element to the DOM and it will work:

    $('body').on('click', '#test', function(event) {
        var link = document.createElement('a');
        // Add the element to the DOM
        link.setAttribute("type", "hidden"); // make it hidden if needed
        link.download = 'test.xls';
        link.href = 'data:application/vnd.ms-excel;utf-8,test';
        document.body.appendChild(link);
        link.click();
        link.remove();
    });
    

    Fiddle

    0 讨论(0)
  • 2020-12-02 18:50

    You don't have to add the element to the DOM, even in FireFox. Replace the .click() method with the following code:

    link.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: true, view: window}));
    

    $('button').on('click', function(event) {
        var link = document.createElement('a');
        link.download = 'test.xls';
        link.href = 'data:application/vnd.ms-excel;utf-8,test';
        link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>Download</button>

    0 讨论(0)
  • 2020-12-02 18:58
      var fileUrl=document.createElement('a');
          fileUrl.href=response.request.responseURL;
          document.body.appendChild(fileUrl);
          fileUrl.click();
    

    add document body, thats working

    0 讨论(0)
提交回复
热议问题