简体   繁体   中英

Trigger click() for dynamically created elements

Ok, there are a couple approaches to the problem of triggering a click() for a dynamically-generated element. First, this will work for Chrome but not IE or FF:

var href="/myUrl";
var link = $("<a>");
link.prop("href", href);
link[0].click()

So, if the thinking is that using click() on an element that doesn't exist won't work in IE or FF, what's the best approach?

var href="/myUrl";
var link = $("<a>");
link.prop("href", href);
$(document).append(link); // Attach it to the DOM so it exists
link[0].click()

Or is there something even simpler that I'm missing? Thanks for any helpful tips.

You've said you want to trigger the download of a file. Another simple way to do that is to have an invisible iframe on the page:

<iframe src="about:blank" style="display: none" id="downloader"></iframe>

...then when you want to trigger the download:

$("#downloader").attr("src", "/myUrl");

As with your current solution, it's important that the response containing the file have a Content-Disposition header identifying it as an "attachment" (the same header can also suggest a name), to get consistent handling across MIME types.

The following is a function that I've used in production code, it's a bit different from yours but it might be what you need.

function psuedoClick(href, target){
    if(!target) target = '_self';
    var falseAnchor = $('<a/>').attr({
        'href' : href,
        'target' : target
    }).appendTo('body');
    falseAnchor[0].click();
    falseAnchor.remove();
};

Just pass in the arguments when you call the function and it'll work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM