具有不同链接的多个社交分享按钮

Multiple social share buttons with different links

this article 的帮助下,我在我的网站上实施了 jQuery 社交分享解决方案。我不得不修改代码,因为我在一个页面上有多个 posts 和这些按钮。我在 PHP 中为按钮容器设置了一个 'data-href' 属性,它为每个 post 显示正确的 link,但脚本只获取第一个的属性,所以每个弹出窗口 window 都尝试共享相同的 post。我应该如何修改此代码以获得不同的 'data-href' 值?

$(document).ready(function(){
var pageTitle   = document.title; //HTML page title
var pageUrl     = $('.share-btn-wrp').attr('data-href');

$('.share-btn-wrp li').click(function(event){
    var shareName = $(this).attr('class').split(' ')[0]; //get the first class name of clicked element
    switch(shareName) //switch to different links based on different social name
    {
        case 'facebook':
            OpenShareUrl('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(pageUrl) + '&title=' + encodeURIComponent(pageTitle));
            break;
        case 'twitter':
            OpenShareUrl('http://twitter.com/home?status=' + encodeURIComponent(pageTitle + ' ' + pageUrl));
            break;
        case 'email':
            OpenShareUrl('mailto:?subject=' + pageTitle + '&body=Found this useful link for you : ' + pageUrl);
            break;
    }

});

function OpenShareUrl(openLink){
    //Parameters for the Popup window
    winWidth    = 650; 
    winHeight   = 450;
    winLeft     = ($(window).width()  - winWidth)  / 2,
    winTop      = ($(window).height() - winHeight) / 2,
    winOptions   = 'width='  + winWidth  + ',height=' + winHeight + ',top='    + winTop    + ',left='   + winLeft;
    window.open(openLink,'Share This Link',winOptions); //open Popup window to share website.
    return false;
}
});

一个共享块的结构如下:

<ul class="share-btn-wrp" data-href="<?php echo $this->item->link; ?>">
  <li class="facebook button-wrap"></li>
  <li class="twitter button-wrap"></li>
  <li class="email button-wrap"></li>
</ul>

听起来你可能需要在某处循环递增。

看来你需要获取被点击按钮的父容器的data-href。试试这个:

$('.share-btn-wrp li').click(function(event){
    var pageUrl = $(this).closest('.share-btn-wrp').attr('data-href');
    var shareName = $(this).attr('class').split(' ')[0]; //get the first class name of clicked element
    switch(shareName) //switch to different links based on different social name
    {
 //etc