在页面上找到相同的href锚点

时间:2019-06-17 04:32:49

标签: javascript jquery anchor href location-href

我想在当前页面上找到具有相同href的锚标记

例如,我在当前页面上有三个具有相同href的锚标记,例如

<a href="https://www.link.com" class="btn btn-cta">

所有按钮的类都是相同的。

对不起,我忘记更新已更新的代码

  $("a").each(function(){
               if ($(this).attr("href") == window.location.pathname){

               }
       });

还有什么更好的方法吗?

任何帮助或建议将不胜感激

预先感谢

1 个答案:

答案 0 :(得分:1)

尝试这样。使用$("[href='"+window.location.pathname+"']")这种方法来查找元素。

var path = window.location.pathname;

$("a[href='"+path+"']").each(function(){
  //do your code here
  console.log(window.location.pathname);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.link.com" class="btn btn-cta">link1</a>
<a href="/js" class="btn btn-cta">link2</a>
<a href="/js" class="btn btn-cta">link3</a>
<a href="https://www.link.com" class="btn btn-cta">link4</a>