关于for循环中进行a标签的点击事件

代码如下: for循环中有两个可以下载文件的a标签,现在只能下载最后一个a标签的文件......

for(var v = 0; v < $("div#downFile a").length; v++){
    $("div#downFile a")[v].click();
}
阅读 8.1k
6 个回答

你还能下载一个也是够给力的。

  • 你看你的代码,你是已经处在使用jquery对象的函数里面,有没有想过,你执行for的时候,你拿到的都是什么。

  • $("div#downFile a")是一个有两个元素的数组,一旦进到for循环里面$("div#downFile a")[v]这个已经是DOM对象了,不是jquery对象了。

  • $($("div#downFile a")[v])这个才是能够用.click()操作的jquery对象

  • jquery封装的东西和原生的DOM或者JS都是有区别的,这也是他敢说Write less, do more的魅力啦。

console.log($("div#downFile a")); // 数组
for(var v = 0; v < $("div#downFile a").length; v++){
    console.log('-----------------');
    
    console.log($("div#downFile a")[v]); // DOM对象
    console.log($($("div#downFile a")[v])); // jquery对象
    
    $("div#downFile a")[v].click(function(){
        console.log($(this)); // 不反应
    });
    
    $($("div#downFile a")[v]).click(function(){
        console.log($(this)); // 输出当前点击对象
    });
}

如果是es6,可以将var 改成 let, 类似这样

for(let v = 0; v < $("div#downFile a").length; v++){
    $("div#downFile a")[v].click();
}

如果是es5,可以使用闭包将v以函数参数形式传递给内层函数

for(var v = 0; v < $("div#downFile a").length; v++){
    (function(v){
        $("div#downFile a")[v].click();
    })(v);
}
$("div#downFile a").each(function(index,item){
    $(this).click();
})

问题已解决,感谢@Huooo的帮助!
代码如下

<div id='downFile'>
    <a href="url1" download="url1"></a>
    <a href="url2" download="url2"></a>
    <button id='btn'>下载</button>
</div>

$(document).on('click', '#btn', function(){
    for(var i=0,lens=$("div#downFile a").length; i<lens; i++){
        $("div#downFile a")[i].click();
    }
});

另附上@Huooo写的一段简单下载文件demo,有需要的可以看下。

$(document).on('click', '#btn', function(){
    var content = '这是一个下载文件的DEMO',
        aTag = document.createElement('a'),
        blob = new Blob([content]);
    aTag.download = 'download.txt';
    aTag.href = URL.createObjectURL(blob);
    aTag.click();
    URL.revokeObjectURL(blob);
});

一定要记得,只要是循环调用函数的,一定要闭包来传参数,否则,肯定都是最后一个值。

牢牢记住!不理解闭包的话,你只需要搜索 setTimeout 闭包,就有最简单的例子,这个应用很广泛。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题