【问题标题】:detect an 'a' tag with href attribute that equals the url of the current page检测具有等于当前页面 url 的 href 属性的“a”标签
【发布时间】:2014-11-25 19:47:10
【问题描述】:

我的任务包含几个步骤:

  1. 隐藏页面中的所有链接
  2. 检测具有等于当前页面 url 的 href 属性的链接元素
  3. 显示此元素的邻居

我使用的html是这样的:

<div class="alllinkswrap">
  <a class="allproductsurls" href="blabla1.com">1</a>
  <a class="allproductsurls" href="blabla2.com">2</a>
  <a class="allproductsurls" href="blabla3.com">3</a>
  <a class="allproductsurls" href="blabla4.com">4</a>
  <a class="allproductsurls" href="blabla5.com">5</a>
</div>

我试图用display: none 隐藏所有链接元素,我只想显示当前链接顶部和底部的2 个链接。我使用的 jQuery 代码:

  $(docment).ready(function(){
  var thispageurl = window.location.href;
   $(".alllinkswrap").children().each(function(){
    if (this.href.indexOf(thispageurl)) 
     {
       $(this).next().show();
       $(this).prev().show();
       }
   });
  });

我猜这个错误出在$(this).next 的某个地方,等等。但对 jQuery 来说还是新手。你能发现问题吗?

【问题讨论】:

  • 那么,如果当前站点是blabla3.com,您想显示blabla2.comblabla4.com
  • 如果window.location.href == this.href.indexOf()将返回0;你的情况将是“假的”。
  • 当然。例如,让我们这样吧
  • @George window.location.href 将始终是完整的 URL,以 http://domain.com/path 开头。所以indexOf 永远不能返回 0。
  • @Barmar 但是这些锚标签的href 属性将是解析的URL,即:http://domain.com/blabla1.com(在这种情况下)?我误解了这个问题吗?

标签: javascript jquery html


【解决方案1】:

原创

您的 indexOf(...) 需要检查非 -1,当未找到 thispageurl in this.href 时,它将返回 -1。或者你可以检查它是否等于 0,因为当找到目标链接时,它应该在索引 0 处找到。

更新

如果您确实想检查当前 URL 和目标 href 是否相等,我们需要在 Javascript 中使用 ===== 比较。这是因为当页面位于子目录中或您在域中时,我们会遇到问题。例如:

如果 thispageurl = http://url.comthis.href = http://url.com/page1.html 使用 this.href.indexOf(thispageurl) 将返回 0,但它不正确。如果我们在这种情况下反转 thispageurl.indexOf(this.href) 的索引,.indexOf() 返回 -1。同样,如果我们将thispageurlthis.href 分别翻转为http://url.com/page1.htmlhttp://url.com,我们会遇到类似的情况,具体取决于我们采用的indexOf。

所以我更新了以下代码来检查字符串值是否相等。

var thispageurl = window.location.href;
$(".alllinkswrap").children().each(function(){$(this).hide()})

$(".alllinkswrap").children().each(function(){
  if (this.href === thispageurl) 
  {
    $(this).next().show();
    $(this).prev().show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="alllinkswrap">
  <a class="allproductsurls" href="blabla1.com">1</a>
  <a class="allproductsurls" href="blabla2.com">2</a>
  <a class="allproductsurls" href="http://stacksnippets.net/js">3</a>
  <a class="allproductsurls" href="blabla4.com">4</a>
  <a class="allproductsurls" href="blabla5.com">5</a>
</div>

【讨论】:

  • 也许你有一些额外的代码?运行上面的 sn -p 会显示链接 2 和 4,这是您想要的功能吗?
  • 上面的代码 sn-p 在文档就绪时触发(即使它不在代码 sn-p 中),请确保保留代码的那部分
  • 好吧,你的代码显然有效,所以,我会试着弄清楚我的代码发生了什么。
  • 嗯,您的链接是动态生成的还是硬编码的?
  • 动态生成
猜你喜欢
  • 1970-01-01
  • 2012-04-07
  • 2021-01-03
  • 1970-01-01
  • 2017-12-18
  • 2018-02-02
  • 2010-11-07
  • 2016-05-25
  • 1970-01-01
相关资源
最近更新 更多