簡體   English   中英

一次將點擊監聽器添加到多個按鈕

[英]add click listener to multiple buttons at once

作為標題,我試圖將單擊偵聽器一次添加到多個按鈕。 但是當我在下面嘗試使用源代碼時,偵聽器已成功添加,但未打開任何鏈接。 我的意思是,當函數向每個元素添加偵聽器時,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;
          })
        }
      });

問題是您正在將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;
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM