Jquery 选择器匹配 link 忽略查询中的 href
Jquery selector to match href in a link ignore query
我的网站上有一些 link 包含 STRING 的 js,它看起来像这样:
if($("a[href*='STRING']").length > 0){
console.log("yes");
}
它 returns 如果有 link 则为真:
<a href="STRING.html">text</a>
问题是 returns 对 link 也是如此:
<a href="index.html?search=STRING">text</a>
如何限制 jquery 选择器只查看 href 的第一部分?
您可以使用 filter()
并与 <a>
中没有查询字符串的 pathname
属性 进行比较。
<a>
元素具有许多类似于 window.location
的属性,如 host
、search
、protocol
等
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>
我的网站上有一些 link 包含 STRING 的 js,它看起来像这样:
if($("a[href*='STRING']").length > 0){
console.log("yes");
}
它 returns 如果有 link 则为真:
<a href="STRING.html">text</a>
问题是 returns 对 link 也是如此:
<a href="index.html?search=STRING">text</a>
如何限制 jquery 选择器只查看 href 的第一部分?
您可以使用 filter()
并与 <a>
中没有查询字符串的 pathname
属性 进行比较。
<a>
元素具有许多类似于 window.location
的属性,如 host
、search
、protocol
等
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>