代码之家  ›  专栏  ›  技术社区  ›  Geoff Appleford

如何选择具有特定文本的所有锚定标记

  •  63
  • Geoff Appleford  · 技术社区  · 16 年前

    给定多个锚定标记:

    <a class="myclass" href="...">My Text</a>
    

    如何选择与类和特定文本匹配的锚定。例如选择所有锚定类:'myclass'和文本:'mytext'

    6 回复  |  直到 16 年前
        1
  •  131
  •   David Morton    16 年前
    $("a.myclass:contains('My Text')")
    
        2
  •  15
  •   Andy E    16 年前

    您可以创建一个自定义选择器,类似于 :contains 对于精确匹配:

    $.expr[':'].containsexactly = function(obj, index, meta, stack) 
    {  
        return $(obj).text() === meta[3];
    }; 
    
    var myAs = $("a.myclass:containsexactly('My Text')");
    
        3
  •  4
  •   karim79    16 年前

    包含 一个特殊的字符串,使用@Dave Morton的解决方案。但是,如果你想 确切地 匹配一个特定的字符串,我建议如下:

    $.fn.textEquals = function(txt) {
        return $(this).text() == txt;
    }
    
    $(document).ready(function() {
        console.log($("a").textEquals("Hello"));
        console.log($("a").textEquals("Hefllo"))
    });
    
    <a href="blah">Hello</a>
    

    修剪

    $.fn.textEquals = function(txt,trim) {
        var text = (trim) ? $.trim($(this).text()) : $(this).text();
        return text == txt;
    }
    
    $(document).ready(function() {
        console.log($("a.myclass").textEquals("Hello")); // true
        console.log($("a.anotherClass").textEquals("Foo", true)); // true
        console.log($("a.anotherClass").textEquals("Foo")); // false
    });
    
    <a class="myclass" href="blah">Hello</a>
    <a class="anotherClass" href="blah">   Foo</a>
    
        4
  •  3
  •   Tchami    11 年前

    $(document).ready(function () {
        $("a:contains('My Text')").each(function () {
            $store = $(this).text();
    
            if ($store == 'My Text') {
                //do Anything.....
            }
        });
    });
    
        5
  •  0
  •   emmics    9 年前

    $(".myClass:contains('My Text')")
    

    如果你甚至不知道它是哪个元素(例如a,p,link,…),你可以使用

    $(":contains('My Text')")
    

    (刚刚离开之前的角色 :

    我必须补充一点,它从 <html> -标记到所需的元素。我能提供的解决方案是 .last() 但只有在只有一个元素可以找到的情况下,这个才有效。也许是斯伯迪。知道更好的解决方法。

    实际上,这应该是对公认答案的补充,尤其是对@Amalgovinus问题。

        6
  •  -2
  •   Brandon    14 年前

    我认为这应该适用于完全匹配的东西。。

    $("a.myclass").html() == "your text"
    
    推荐文章