【问题标题】:Jquery selector to match href in a link ignore query用于匹配链接忽略查询中的 href 的 Jquery 选择器
【发布时间】:2019-08-23 03:59:01
【问题描述】:

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

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】:

    您可以使用filter() 并与&lt;a&gt;pathname 属性进行比较,其中没有查询字符串。

    &lt;a&gt; 元素有许多类似于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>

    【讨论】:

    • OK...我刚刚添加了一个长度检查和日志,您可以使用它。从你的中删除 css(),它只是作为演示的一部分来展示它捕获的内容
    • 谢谢!
    • 哦,这对我来说更有意义,现在让我试试看。
    猜你喜欢
    • 2021-05-11
    • 2014-07-27
    • 2012-01-30
    • 1970-01-01
    • 2023-02-26
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多