我在this article的帮助下在我的网站上实现了一个jQuery社交共享解决方案。我不得不修改代码,因为我在一个页面上有多个帖子和这些按钮。我为PHP中的按钮容器设置了'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>
答案 0 :(得分:1)
看起来您需要获取所点击按钮的父容器的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
答案 1 :(得分:0)
听起来你可能需要一个循环来增加。