0

我正在尝试实现一种方法来检查当前页面上的链接使用点击是否相同,什么都不会发生。否则转到链接用户单击的位置。我知道

var pathname = window.location.pathname;

获取当前链接。但不确定当用户点击时如何获取链接...

非常感谢 ...

4

3 回答 3

1

将点击事件绑定到所有链接。我会location.href用来获取相同的页面,而不是.pathname太。

​$("a").click(function() {
    var pathname = window.location.href;
    console.log(pathname);
    if (this.href == pathname) {
        alert ("Same site. no go");
        return false;
    }
})​​
于 2012-07-05T15:16:14.077 回答
1

假设您使用的是 1.7 及更高版本,这将更新页面上的所有链接和未来链接。

$("a").on("click", function(){
   var linkAddress = $(this).attr('href');
   if(linkAddress==pathname){
      return false;
   }
   return true;
});
于 2012-07-05T15:16:18.480 回答
0

你可以用这个变量剥离锚点

var anchor = document.location.hash; 

并检查留下了什么。例子

$(".button").click(function(){
   var anchor = document.location.hash;
   if ( anchor === '#myLink1' ) {//u can set ( if same page do nothing here)
     alert('ok');
   }else{ alert('not ok');}
});

html

<a class="button" href="#myLink1">1</a>
于 2012-07-05T15:21:59.073 回答