2013-10-25 64 views
0

自動參考頁面URL如何引用當前頁面的URL?<a></a><a></a>標籤

我在幾頁上有一個共享微博按鈕。我希望能夠自動引用當前頁面的URL,因此當用戶點擊「發送此頁面」時,會在Twitter推文框中生成該URL。我希望這樣做的原因是我可以從一個地方管理按鈕,而不是幾個頁面。

HTML(目前,該網址是手動粘貼到該鏈接的href標記。

<a href="http://dangfoods.com/coconutchips.php" title="These chips are great for you HEALTH!! #dangfoods" class="tweetDialog" target="_blank"><div id="tweets-btn" class="custom-button">Tweet This Page</div></a> 

當前的Javascript

// We bind a new event to our link 
$('a.tweetDialog').click(function(e){ 
    //We tell our browser not to follow that link 
    e.preventDefault(); 
    //We get the URL of the link 
    var loc = $(this).attr('href'); 
    //We get the title of the link 
    var title = escape($(this).attr('title')); 
    //We trigger a new window with the Twitter dialog, in the middle of the page 
    window.open('http://twitter.com/share?url=' + loc + '&text=' + title + '&', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0'); 
}); 
+1

你的問題是什麼? – ComFreek

+0

對不起@ComFreek,我想引用這個URL,所以當用戶點擊twitter按鈕時,這個URL會自動放入對話框彈出框中。目前,我必須手動將網址放入href屬性中。我寧願擁有它,我可以在全球管理一個按鈕,而不是每個頁面。 –

回答

1

你想用的,而不是href屬性當前頁面的網址是什麼?更改

var loc = $(this).attr('href'); 

var loc = location.href; 

或者你可以生成Twitter分享URL服務器端,把它放在href屬性,那麼在停止的onclick默認處理程序,並鏈接目標打開的窗口。這樣,您的鏈接將無需JavaScript即可運行。

+0

這很有幫助。原來我只是需要把「window.location.href」。謝謝! –

1

您可以使用「location.href」獲取頁面的URL,並使用「document.title」獲取當前頁面的標題。試試這個:

$('a.tweetDialog').click(function(e){ 
    //We tell our browser not to follow that link 
    e.preventDefault(); 

    //We get the URL of the link 
    var loc = location.href; 
    //We get the title of the link 
    var title = escape(document.title); 

    //We trigger a new window with the Twitter dialog, in the middle of the page 
    window.open('http://twitter.com/share?url=' + loc + '&text=' + title + '&', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0'); 
}); 
+1

請不要鏈接到[w3schools](http://www.w3fools.com)。 –

+0

感謝您的迴應,標題是一個功能,但是,location.href不會將鏈接放在twitter對話框中。如果您訪問www.dangfoods.com/coconutchips.php,您會看到我想要實現的目標,但無需手動編輯每個頁面上的按鈕。 –

+0

這很有幫助,結果只是需要「window.location.href」才能正常工作。謝謝! –