gpt4 book ai didi

javascript - 一次为多个按钮添加点击监听器

转载 作者:行者123 更新时间:2023-12-03 05:50:11 25 4
gpt4 key购买 nike

如标题所示,我正在尝试一次向多个按钮添加点击监听器。但是当我尝试下面的源时,监听器添加成功,但它没有打开任何链接。我的意思是,当函数向每个元素添加监听器时,socialLinks 数组未定义。有人可以帮助我吗?

$('.IndexBody').arrive('#shortUrl', function(){
var shortUrl = $('#shortUrl').text();
var socialTags = ['.entypo-twitter', '.entypo-facebook', '.entypo-gplus'];
var socialLinks = ["http://twitter.com/share?text=http://"+shortUrl+" — Link made by ",
"https://www.facebook.com/sharer/sharer.php?u="+shortUrl+"&src=sdkpreparse",
"https://plus.google.com/share?url="+shortUrl];
console.log(socialLinks);
for(var i=0; i<3; i++){
$(socialTags[i]).click(function(e) {
var width = 575,
height = 400,
left = ($(window).width() - width) / 2,
top = ($(window).height() - height) / 2,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
window.open(socialLinks[i], 'facebook', opts);
console.log(socialLinks[i]);
return false;
})
}
});

最佳答案

问题是您正在 closure 内捕获 i ,因此单击按钮时的值将是当前值,而不是创建函数时的值。

尝试这样的事情:

for(var i=0; i<3; i++){
$(socialTags[i]).click(createHandler(socialLinks, i));
}

function createHandler (socialLinks, i) {
return function (e) {
var width = 575,
height = 400,
left = ($(window).width() - width) / 2,
top = ($(window).height() - height) / 2,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
window.open(socialLinks[i], 'facebook', opts);
console.log(socialLinks[i]);
return false;
};
}

关于javascript - 一次为多个按钮添加点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40187984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com