使用JS捕获链接ID然后直接链接

时间:2016-03-12 06:31:46

标签: javascript jquery

我有一个跨越不同子域的活动网站。在子域中,我有链接通向俱乐部网页。我没有为俱乐部提供许多链接,而是希望有一个JavaScript文件来捕获特定的“俱乐部链接”,但我被卡住了。我的代码到目前为止..谢谢。我也希望他们在新标签中打开。

function clubs() {
  $("a#club1").on('click', function() {
    window.location = "http://www.club.com/club1.html", "_blank";
  });
  $("a#club2").on('click', function() {
    window.location = "http://www.club.com/club2.html", "_blank";
  });
  $("a#club3").on('click', function() {
    window.location = "http://www.club.com/club3.html", "_blank";
  });
}
<div class="content">
  <div class=""><a id="club1" href="javascript:clubs()">club1</a>
  </div>
  <div class=""><a id="club2" href="javascript:clubs()">club2</a>
  </div>
  <div class=""><a id="club3" href="javascript:clubs()">club3</a>
  </div>
</div>

3 个答案:

答案 0 :(得分:2)

使用window.open("http://www.club.com/club1.html", "_blank")代替window.location

答案 1 :(得分:1)

您有一个函数clubs,它将事件处理程序附加到<a>标记。此函数应该只运行一次,或者它的函数部分被丢弃,因此它变成内联代码。一旦通过jquery分配处理程序,就不需要那些内联事件处理程序。另外,正如Hank所提到的,使用window.open而不是window.location。

<div class="content">
  <div class=""><a id="club1" href="javascript:void(0)">club1</a>
  </div>
  <div class=""><a id="club2" href="javascript:void(0)">club2</a>
  </div>
  <div class=""><a id="club3" href="javascript:void(0)">club3</a>
  </div>
</div>
<script>
      $("a#club1").on('click', function() {
        window.open("http://www.club.com/club1.html", "_blank");
      });
      $("a#club2").on('click', function() {
        window.open("http://www.club.com/club2.html", "_blank");
      });
      $("a#club3").on('click', function() {
        window.open("http://www.club.com/club3.html", "_blank");
      });
</script>

答案 2 :(得分:1)

好的,我遇到了你的问题...你需要做一些如下的技巧:
HTML:

<div class="content">
  <div class=""><a href="#" id="club1">club1</a>
  </div>
  <div class=""><a href="#" id="club2">club2</a>
  </div>
  <div class=""><a href="#" id="club3">club3</a>
  </div>
</div>

<强> JS:

$(document).ready(function(){
  $("a#club1").on('click', function() {
    var win = window.open("http://www.club.com/club1.html", '_blank');
    win.focus();
  });
  $("a#club2").on('click', function() {
    var win = window.open("http://www.club.com/club2.html", '_blank');
    win.focus();
  });
  $("a#club3").on('click', function() {
    var win = window.open("http://www.club.com/club3.html", '_blank');
    win.focus();
  });
});


Click This fiddle link