sourcetip

특정 텍스트가 포함된 모든 앵커 태그를 선택하는 방법

fileupload 2023. 10. 30. 21:13
반응형

특정 텍스트가 포함된 모든 앵커 태그를 선택하는 방법

여러 개의 앵커 태그가 지정된 경우:

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

수업과 일치하는 앵커와 특정 텍스트를 선택하려면 어떻게 해야 합니까?eg 클래스가 있는 모든 앵커를 선택합니다. '내 클래스' 및 텍스트: '내 텍스트'

$("a.myclass:contains('My Text')")

다음과 유사한 사용자 지정 선택기를 만들 수 있습니다.:contains정확한 일치 항목:

$.expr[':'].containsexactly = function(obj, index, meta, stack) 
{  
    return $(obj).text() === meta[3];
}; 

var myAs = $("a.myclass:containsexactly('My Text')");

앵커의 텍스트에 특정 문자열이 포함되어 있는 경우에만 신경이 쓰일 경우 @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>

먼저 'MY text'가 포함된 모든 태그를 선택합니다.그런 다음 정확한 매치마다 조건과 일치하면 원하는 것을 수행합니다.

$(document).ready(function () {
    $("a:contains('My Text')").each(function () {
        $store = $(this).text();

        if ($store == 'My Text') {
            //do Anything.....
        }
    });
});

원하는 객체의 클래스를 모르고 링크 텍스트만 따라가려고 한다면 사용할 수 있습니다.

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

어떤 요소인지(예: a, p, link, ...)도 모른다면 사용할 수 있습니다.

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

(그전에 파트를 떠나는 것뿐):공란)

여기에 덧붙이자면 모든 요소가 시작됩니다.<html>- 원하는 요소까지 태그를 지정합니다.제가 제공할 수 있는 솔루션은 다음과 같습니다..last()하지만 이것은 오직 하나의 요소만 찾을 수 있을 때만 작동합니다.아마 누군가.여기서 더 나은 해결책을 알고 있습니다.

사실, 이것은 특히 @Amalgovinus 질문에 수용된 답변에 추가되어야 합니다.

정확한 일치를 위해서는 이것이 효과가 있을거라 생각합니다.

$("a.myclass").html() == "your text"

언급URL : https://stackoverflow.com/questions/2446936/how-to-select-all-anchor-tags-with-specific-text

반응형