一次将click监听器添加到多个按钮

时间:2016-10-22 03:22:29

标签: javascript jquery window.open

作为标题,我试图立即将点击​​监听器添加到多个按钮。 但当我尝试下面的源代码时,Listener成功添加了,但它没有打开任何链接。我的意思是当函数向每个元素添加侦听器时,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;
          })
        }
      });

1 个答案:

答案 0 :(得分:1)

问题是你在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;
    };
}