2009-05-25 17 views
6

ho questo html:come selezionare solo il testo dell'elemento superiore?

<span class="price"> 
     $61.00 
       <span class="detailFreeShipping">With Free Shipping</span> 
    </span> 

Come scrivere un selettore jQuery, che mi danno il testo di prezzi soltanto "$ 61.00"?

voglio renderlo generico come posso perché potrebbe essere in alcuni casi non c'è intervallo interno, solo quello genitore.

risposta

11

Si può fare questo:

jQuery.fn.extend({ 
    textOnly: function() { 
     // make a clone of this object so we are not changing the actual DOM 
     var obj = $(this).clone(); 

     // remove all the children, i.e. any DOM objects 
     obj.children().remove(); 

     // get the text value after all DOM elements are removed 
     return obj.text(); 
    } 
}); 

allora si può chiamare così

var price = $(".price").textOnly(); 

otterrete il valore desiderato.

+0

sostituire semplicemente "textOnly =" con "textOnly:" –

+0

Grazie, l'ho avuto come funzione autonoma, ma ho deciso di estenderlo all'ultimo minuto. –

0

Non so jQuery, ma solo per pseudo-rispondere alla tua domanda, è possibile effettuare questa operazione:

var elem = document.getElementById('yourid'); // or document.getElementsByTagName('span')[0]; 
var text = elem.innerHTML; 
text = text.substr(0, (text.indexOf('<') > -1 ? text.indexOf('<') : text.length)); 
0

tentativo:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
    <script type="text/javascript" charset="utf-8"> 
     google.load("jquery", "1.3"); 
    </script> 
    <script type="text/javascript" charset="utf-8"> 
     $(document).ready(function(){ 
      var white_out = $("span[class=price] :first-child").text(); 
      var all = $("span[class=price]").text(); 
      var price = all.replace(white_out, ""); 
      alert(price); 
     }); 
    </script> 
</head> 
<body> 
    <span class="price"> 
      $61.00 
       <span class="detailFreeShipping">With Free Shipping</span> 
     </span> 
</body> 
</html> 

dove le linee:

  var white_out = $("span[class=price] :first-child").text(); 
      var all = $("span[class=price]").text(); 
      var price = all.replace(white_out, ""); 

potrebbe fare il lavoro, per un singolo elemento.

+0

cosa succede se il prezzo è il secondo nell'elemento? l'autore originale ha chiesto che fosse il più generico possibile. –

+0

quindi funziona ancora, perché il primo figlio viene eliminato, poiché nella tua (più elegante) soluzione tutti gli elementi figli vengono eliminati. l'ordine non ha importanza, né se esiste un elemento figlio; lo considero "generico possibile" per il problema presentato ... – miku

Problemi correlati