0
function clickLink(link) {     
var cancelled = false;
if (document.createEvent) {
    var event = document.createEvent("MouseEvents");
    event.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0,
        false, false, false, false,
        0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }
    if (!cancelled) {
        window.location = link.href;
    }
}

for (var i = 0; i < links.length; i++) { 
    var x=links[i];
    if(x.href.indexOf('download.mp4') > -1) { 
        console.log(x.href); x.click(); 
        }
    } 
for (var i = 0; i < links.length; i++) { 
    var x=links[i];
    if(x.href.indexOf('download.mp4') > -1) {
        console.log(x.href); clickLink(x); 
    }
}

使用上面的代码,目的是在一页上下载所有视频链接。尽管控制台日志包含所有链接,但我只希望真正下载一个链接。没有错误或警告,我该如何实现?也试过没有 window.location 线,没有运气......

现在解决了以下问题:

function JustclickLink(link) {     
       var cancelled = false;
if (document.createEvent) {
    var event = document.createEvent("MouseEvents");
    event.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0,
        false, false, false, false,
        0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
    window.open(link.href,'_blank');         
    }
}
   for (var i = 0; i < links.length; i++){ 
    var x=links[i];
    if(x.href.indexOf('download.mp4') > -1){
        console.log(x.href); JustclickLink(x); 
    }
}
4

1 回答 1

0

这是您所寻求的 jquery 替代方案。Window.open 应该用于多次下载,因为 window.location 只会在代码运行中触发一次。

$('#foo').on('click', function() {
window.open($(this).attr("href"),'_blank');
});
$('#foo').trigger('click');
于 2013-08-23T06:28:55.027 回答