0

現在のページの URL を参照するにはどうすればよいですか?

いくつかのページに Twitter の共有ボタンがあります。現在のページの URL を自動的に参照できるようにして、ユーザーが「このページをつぶやく」をクリックすると、Twitter のつぶやきボックスに URL が生成されるようにしたいと考えています。これを行う理由は、複数のページではなく 1 か所からボタンを管理できるようにするためです。

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');
});
4

2 に答える 2

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');
});
于 2013-10-25T21:05:24.520 に答える
1

href属性の代わりに現在のページの URL を使用しますか? 変化する

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

var loc = location.href;

または、サーバー側で Twitter 共有 URL を生成し、それをhref属性に配置してから、onclick でデフォルト ハンドラを停止し、リンク ターゲットでウィンドウを開くことができます。そうすれば、リンクは JavaScript なしで機能します。

于 2013-10-25T21:02:55.277 に答える