-1

我有以下三个代码块,想知道是否可以以某种方式将它们组合起来,这样我就不必一遍又一遍地编写相同的代码。对不起,如果我解释这个有趣。我只想学习尽可能优雅/高效地写作。

HTML

<a href="#" id="download-1">Tweet to Download</a></li>
<a href="#" class="download1">Download</a></li>

<a href="#" id="download-2">Tweet to Download</a></li>
<a href="#" class="download2">Download</a></li>

<a href="#" id="download-3">Tweet to Download</a></li>
<a href="#" class="download3">Download</a></li>

1

  // Download 1
  $('#download-1').tweetAction({
    url: 'download1',
    text: 'Download 1',
    via: 'twittersn'
  },function(){
    // When the user closes the pop-up window:

    $('a.download1')
      .addClass('active')
      .attr('href','download1.psd');
  });

2

  // Download 2
  $('#download2').tweetAction({
    url: 'download2',
    text: 'Download 2',
    via: 'twittersn'
  },function(){
    // When the user closes the pop-up window:

    $('a.download2')
      .addClass('active')
      .attr('href','download2.psd');
  });

3

  // Download 3
  $('#download3').tweetAction({
    url: 'download3',
    text: 'Download 3',
    via: 'twittersn'
  },function(){
    // When the user closes the pop-up window:

    $('a.download3')
      .addClass('active')
      .attr('href','download3.psd');
  });
4

1 回答 1

2

只需包含在一个函数中,因此:

function tweetFunc(id) {
    $('#download-' + id).tweetAction(
        {
            url: 'download' + id,
            text: 'Download ' + id,
            via: 'twittersn'
        },
        function() {
            // When the user closes the pop-up window:
            $('a.download' + id)
                .addClass('active')
                .attr('href','download' + id + '.psd')
            ;
        }
    );
}

for(i = 1; i <= 3; i++) {
    tweetFunc(i);
}

要使其正常工作,您需要同步下载 id 属性的格式:是它download-X还是downloadX

于 2013-04-15T20:46:25.183 回答