仅定位相同的网页锚点链接

时间:2018-02-08 03:51:29

标签: javascript jquery anchor hashchange

从任何给定网站的网络分析师的角度来看,我正在寻找控制台中最常点击哪个相同的页面锚点,现在在控制台中记录锚点的文本值(内部html文本)。

我采取的方法是在每次锚定点击后获取当前页面URL并检查它们是否在url字符串末尾有任何哈希值更改,如果是,则在控制台中打印该锚点的文本值。

var anchor = $("a[href^=\\#]");

anchor.on("click", function(){
    if("onhashchange" in window) {
        var anchorText = this.text;
        console.log(anchorText);
}
});

我遇到了我编写的代码的问题,因为它返回页面上任何锚点的内部Html文本(除了带有外部链接的那些)但我只想跟踪导致相同部分的那些页。

我采取的方法是否需要修改甚至开始?

以下是我正在使用的一些html以及我想跟踪的不同锚点以及我不想跟踪的那些。

 <!-- Where the click on the anchor i want to target happens  -->
  <nav>
   <h2 class="wb-inv">Promotions</h2>
     <ul class="toc lst-spcd col-md-12">
       <li class="col-md-4">
         <a href="#story1" class="list-group-item">Anchor for section 1</a>
       </li>
    </nav>

 <!-- below is the section of the same page the anchors would point to -->
  <div class="col-md-12 pull-left">
    <h2 id="story1">Section 1 Title </h2>
      <p>Random paragraph 1</p> 
   </div>

 <!-- The html I'm working with contains a set of tabs that reveal information as you click them, the href attribute and the id are both in the anchor. This is an example of anchors I wouldn't want to track-->
  <a tabindex="-1" id="details-panel1-lnk" role="tab" aria-selected="false" aria-controls="details-panel1" href="#details-panel1">
   <h2 class="h5 mrgn-tp-sm mrgn-bttm-sm">Online</h2>
  </a>

2 个答案:

答案 0 :(得分:0)

记录导航到页面上元素的锚点。

&#13;
&#13;
$(document).ready(function() {
   var anchor = $("a[href^=\\#]");
   var url = $(window);

   anchor.on("click", function(e){
     if ( $('#' + $(this).text()).length ) {
          console.log($(this).text());
     }
   });
})
&#13;
.section {
   height: 400px;
}
.section:nth-child(even) {
   background: grey;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section" id="one">
	<a href="#one">one</a>
</div>
<div class="section" id="two">
	<a href="#two">two</a>
</div>
<div class="section" id="three">
	<a href="#three">three</a>
</div>
<div class="section" id="four">
	<a href="#four">four</a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var anchor = $("a[href^=\\#]").not("a[href=#shr-pg0]");

   anchor.on("click", function(){
      var anchorText = this.text;
      $(window).one("hashchange",function() {
        console.log(anchorText);
     });
  });