【问题标题】:targeting only same page anchor links仅针对同一页面的锚链接
【发布时间】:2018-02-08 03:51:29
【问题描述】:

从任何给定网站的网络分析师的角度来看,我正在寻找通过控制台在控制台中记录锚的文本值(内部 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>

【问题讨论】:

  • if ('onhashchange' in window) 不检查事件是否发生,只是检查浏览器是否支持该类型的事件。

标签: javascript jquery anchor hashchange


【解决方案1】:

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

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

   anchor.on("click", function(e){
     if ( $('#' + $(this).text()).length ) {
          console.log($(this).text());
     }
   });
})
.section {
   height: 400px;
}
.section:nth-child(even) {
   background: grey;
}
<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>

【讨论】:

  • 感谢您的回复。我希望只在单击的锚点上获得内部 html 文本。我的主要问题是我只想过滤导航到同一页面区域的锚点,目前它为任何锚点捕获文本,无论它是否符合该标准。
  • 您是否只想跟踪指向页面特定区域的点击?而不是一般的同一页面?
  • 是的,所以在给定页面中,只跟踪跳转到同一页面任何区域的锚点的点击,我会忽略其他任何其他锚点。
  • 您能否提供一个您正在使用的 html 示例?这将有助于了解您正在使用的结构。我用一个 sn-p 更新了我的答案,它根据被点击的锚点的 id 检查现有元素。
  • 感谢您的帮助!对于我正在使用的网站,我经常遇到一些“共享此页面”按钮的问题。我必须包含 .not() 对象才能从我想要定位的其他锚点中省略它。我结束了我的代码修复并提出了以下解决方案
【解决方案2】:
var anchor = $("a[href^=\\#]").not("a[href=#shr-pg0]");

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2015-12-08
    • 2019-08-08
    • 2015-03-29
    相关资源
    最近更新 更多