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

Javascript 具有不同链接的多个社交共享按钮,javascript,jquery,social-networking,share-button,Javascript,Jquery,Social Networking,Share Button,在的帮助下,我在我的网站上实现了jQuery社交共享解决方案。我不得不修改代码,因为我在一个页面上有多篇带有这些按钮的文章。我在PHP中为buttons容器设置了一个“data href”属性,它为每个帖子显示正确的链接,但是脚本只获取第一个帖子的属性,因此每个弹出窗口都尝试共享同一个帖子。我应该如何修改此代码以获得不同的“data href”值 $(document).ready(function(){ var pageTitle = document.title; //HTML page

在的帮助下,我在我的网站上实现了jQuery社交共享解决方案。我不得不修改代码,因为我在一个页面上有多篇带有这些按钮的文章。我在PHP中为buttons容器设置了一个“data href”属性,它为每个帖子显示正确的链接,但是脚本只获取第一个帖子的属性,因此每个弹出窗口都尝试共享同一个帖子。我应该如何修改此代码以获得不同的“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>

听起来您可能需要在某个地方增加一个循环。

看起来您需要获取所单击按钮的父容器的
数据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

如果我理解HTML,您需要找到
$(this)
的父项并获取其
数据href
父项是
。共享btn wrp
,但脚本只获取第一个的
数据href
。我已为问题添加了确切的结构。