Download File Using Javascript/jQuery

前端 未结 28 3465
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

28条回答
  •  萌比男神i
    2020-11-21 05:39

    I suggest you use the mousedown event, which is called BEFORE the click event. That way, the browser handles the click event naturally, which avoids any code weirdness:

    (function ($) {
    
    
        // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
        $(document).ready(function () {
    
            var url = '/private/downloads/myfile123.pdf';
            $("a#someID").on('mousedown', function () {
                $(this).attr("href", url);
            });
    
        });
    })(jQuery);
    

提交回复
热议问题