如何引用当前页面 URL?
我在几个页面上有一个分享 Twitter 按钮。我希望能够自动引用当前页面 URL,以便当用户单击“推特此页面”时,URL 会在 twitter 推文框中生成。我希望这样做的原因是我可以从一个地方而不是多个页面管理该按钮。
HTML(目前,url 手动粘贴到链接中的 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');
});
最佳答案
您想使用当前页面 URL 而不是 href
属性?改变
var loc = $(this).attr('href');
至
var loc = location.href;
或者您可以在服务器端生成 Twitter 共享 URL,将其放入 href
属性中,然后在 onclick 中停止默认处理程序并打开带有链接目标的窗口。这样您的链接就可以在没有 JavaScript 的情况下工作。
关于javascript - <a></a> 标签内的自动引用页面 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19599175/