代码之家  ›  专栏  ›  技术社区  ›  CeejeeB

如何根据元素的内容选择元素?

  •  2
  • CeejeeB  · 技术社区  · 16 年前

    我需要能够选择具有特定内容的元素(innerhtml)。

    例如,我有一些锚,每个锚都有一个数字作为文本。如何选择文本为“1”的锚?

    我试过这个

    $('a[innerHTML="1"]')
    

    这似乎在IE中有效,但不是FF或Chrome!

    3 回复  |  直到 16 年前
        1
  •  1
  •   andres descalzo    16 年前
        2
  •  1
  •   ryanulit    16 年前

    Try$(“A:包含(‘1’)”)

    edit=>如果找不到任何内容,这将仅用1或空提示锚定的文本。

    alert(FindLink($("a:contains('1')"), "1"));
    
    function FindLink(element, textToFind) {
        var result = null;
        element.each(function() {
            if ($(this).text() === textToFind)
            {
                result = $(this).text();
                // you can change any attributes or css using $(this).css, etc
                // once the if statement is satisfied
            }
        });
        return result;
    }
    
        3
  •  0
  •   CeejeeB    16 年前

    谢谢你的回复。我想出了一个解决办法:

    $('.pages a').filter(function() { return $(this).text() == 1; } )
    

    由于我正在搜索的锚都在一个公共分区中,所以我通过该分区缩小范围,然后运行一个客户过滤器函数来查找准确的元素。