【问题标题】:How to get an element by its href in jquery?如何在jquery中通过href获取元素?
【发布时间】:2011-03-07 13:35:26
【问题描述】:

我想通过 jquery 或 javascript 中的 href 属性获取元素。这可能吗?

【问题讨论】:

    标签: javascript jquery html javascript-framework


    【解决方案1】:

    是的,你可以使用 jQuery 的 attribute selector 来实现。

    var linksToGoogle = $('a[href="https://google.com"]');
    

    或者,如果您的兴趣是开始与某个 URL 的链接,请使用 attribute-starts-with 选择器:

    var allLinksToGoogle = $('a[href^="https://google.com"]');
    

    【讨论】:

      【解决方案2】:

      如果您想获取在其 href 属性中包含部分 URL 的任何元素,您可以使用:

      $( 'a[href*="google.com"]' );
      

      这将选择包含 google.com 的 href 的所有元素,例如:

      正如@BalusC 在下面的 cmets 中所述,它还将匹配在 href 中的任何位置具有 google.com 的元素,例如 blahgoogle.com

      【讨论】:

      • 它还天真地匹配blahgoogle.comsome.com?blah=google.com。不好的建议。
      • @BalusC 如所述:any element that has part of a URL in their href attribute.
      【解决方案3】:
      var myElement = $("a[href='http://www.stackoverflow.com']");
      

      http://api.jquery.com/attribute-equals-selector/

      【讨论】:

        【解决方案4】:

        是的。

        $('a[href=\'http://google.com\']')
        

        http://api.jquery.com/attribute-equals-selector/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-26
          • 2012-02-14
          • 2015-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多