2012-02-24 13 views

risposta

73

http://api.jquery.com/contains-selector/

$("span:contains('FIND ME')") 

ETA:

Il contiene selettore è bello, ma filtrare un elenco di campate se probabilmente più veloce: http://jsperf.com/jquery-contains-vs-filter

$("span").filter(function() { return ($(this).text().indexOf('FIND ME') > -1) }); -- anywhere match 
$("span").filter(function() { return ($(this).text() === 'FIND ME') }); -- exact match 
+2

risponde alla mia domanda successiva? http://stackoverflow.com/questions/9424509/how-do-i-select-a-span-contain-an-exact-text-value-using-jquery – MedicineMan

+0

Sì. Il filtro è di nuovo la risposta, ma questa volta si controlla l'intero valore .text() per una corrispondenza anziché cercare l'indice. Risposta aggiornata – Malk

+0

Grazie Malk! Non avevo sentito parlare di filter(). A volte è necessario in quanto contiene() è un confronto con caratteri jolly, quindi troverai "TROVA ME" e "NON TROVARE ME" che non è utile se hai bisogno di una corrispondenza esatta – Peadar

9

Usa contains:

$("span:contains('FIND ME')") 
2

penso che questo funzionerà

var span; 
$('span').each(function(){ 
    if($(this).html() == 'FIND ME'){ 
    span = $(this); 
    } 
}); 
+1

Oh sì. Queste altre risposte sono molto meglio. Usa quelli. – buck54321

1

A proposito, se si desidera utilizzare questo con una variabile, che ci si fa in questo modo:

function findText() { 
    $('span').css('border', 'none'); //reset all of the spans to no border 
    var find = $('#txtFind').val(); //where txtFind is a simple text input for your search value 
    if (find != null && find.length > 0) { 
     //search every span for this content 
     $("span:contains(" + find + ")").each(function() { 
      $(this).css('border', 'solid 2px red'); //mark the content 
     }); 
    } 
} 
Problemi correlati