2014-05-05 52 views
-3

我是使用JavaScript的新用戶,並且我試圖將Google Plus「分享」按鈕附加到我博客索引頁上的每個博客文章。爲此,我使用下面的JavaScript代碼。將Google Plus按鈕添加到我的博客文章時遇到問題

理論上,這應該提取我的頁面的主URL和每個a.blog-title-link(href)。但是,出現在google分享按鈕上的鏈接對於每個帖子都是相同的。對於每個博客文章共享鏈接,我得到這個:/3/post/2014/04/this-is-6post.html。 小提琴Example

我試過使用.map()函數,但無濟於事。

<body> 
    <div class='blog-index-page'> 

    <div class='blog-post'> 
    <div class='blog-header'> 
    <h2 class='blog-title'> 
    <a href='/3/post/2014/04/this-is-6post.html' class='blog-title-link' class='blog-link'>THIS IS POST 6</a> 
    </h2> 
    </div> 
    </div> 

    <div class='blog-post'> 
    <div class='blog-header'> 
     <h2 class='blog-title'> 
    <a href='/3/post/2014/04/this-is-5post.html' class='blog-title-link' class='blog-link'>THIS IS 5 POST</a> 
    </h2> 
    </div> 
    </div> 

    <div class='blog-post'> 
    <div class='blog-header'> 
     <h2 class='blog-title'> 
     <a href='/3/post/2014/04/this-is-4post.html' class='blog-title-link' class='blog-link'>THIS IS 4POST</a></h2> 
    </div> 
    </div> 

     </div> 

    var uri = $('a.blog-title-link').attr('href'); 

    var res = (uri); 

$('div.blog-post').each(function(){ 
$(this).append('<a href="https://plus.google.com/share?url='+(window.location.origin)+''+(uri)+'">shareplus</a>'); 
}); 


    </body> 
+0

你得到了什麼錯誤? –

+0

我得到相同的頂部鏈接href ='/ 3/post/2014/04/this-is-6post.html',用於所有帖子的谷歌分享鏈接。 – user3604548

回答

1
var uri = $('a.blog-title-link').attr('href'); 
      ^^^^^^^^^^^^^^^^^^^^^---- a) 
            ^^^^^^^^^^^--- b) 

一)$(..)代碼檢索所有<a class="blog-title-link">元素的整個文檔

二).attr()調用,然後得到FIRST的href在元素的)

返回你可能想要的東西更像

$('div.blog-post').each(function(obj){ 
     var uri = $(obj).find('a.blog-title-link').attr('href'); 
}); 

使用此功能,您需要在個人div.blog-post元素內搜索您的<a>標籤。例如不是在DOM樹中查找所有的<a>標籤,而是在尋找當前樹分支中的一個。

+0

謝謝Marc B,但這裏不工作是我做的(http://jsfiddle.net/vMdYR/41/)的一個小提琴鏈接嘗試你的代碼,但谷歌鏈接消失。 – user3604548

相關問題