Jquery选择器匹配链接忽略查询中的href

问题描述 投票:0回答:1

我的网站上有一些js包含STRING的链接,它看起来像这样:

if($("a[href*='STRING']").length > 0){
    console.log("yes");
}

如果有如下链接,则返回true:

<a href="STRING.html">text</a>

问题是它也返回true,如下所示:

<a href="index.html?search=STRING">text</a>

如何限制jquery选择器只查看href的第一部分?

jquery jquery-selectors
1个回答
3
投票

您可以使用filter()并与pathname<a>属性进行比较,该属性中没有查询字符串。

<a>元素有许多类似于window.location的属性,如hostsearchprotocol等。

pathname在域名主持人之后开始并在任何#?之前结束

var $hasString= $('a').filter(function() {
  console.log(this.pathname)
  return this.pathname.includes("STRING");
}).css('color', 'red');

console.log("Matches:", $hasString.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="STRING.html">No search </a><br/><br/>
<a href="index.html?search=STRING">Search</a>
© www.soinside.com 2019 - 2024. All rights reserved.