2012-12-27 12 views
9

Come posso ottenere valori di TD in una tabella HTML?Ottieni valori di celle di tabella HTML in una riga facendo clic su di esso

cioè

| ID | cell 1 | cell 2 | 
| 1 | aaaa | a2a2a2 | 
| 2 | bbbb | b2b2b2 | 
| 3 | cccc | c2c2c2 | 

Così ora se clicco sul valore della cella: "bbbb" Voglio ottenere tutti i valori della riga selezionata:

$id='2'; $cell_1='bbbb'; $cell_2='b2b2b2'; 

NOTA: mi piacerebbe piace usare JavaScript e non jQuery.

risposta

13

È possibile utilizzare event.target.innerText per javascript e $ (event.target) .text() per jQuery, jQuery è la soluzione preferita in quanto gestisce cross browser competibilities.

Utilizzando solo javascript

Live Demo

Html

<table id="tableID" onclick="myFun(event)" border="1"> 
    <tr> 
    <td>row 1, cell 1</td> 
    <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
    <td>row 2, cell 1</td> 
    <td>row 2, cell 2</td> 
    </tr> 
</table>​ 

Javascript

function myFun(e){ 
    alert(e.target.innerText); //current cell 
    alert(e.target.parentNode.innerText); //Current row. 
}​ 

utilizzando jQuery

Live Demo

Html

<table id="tableID" border="1"> 
    <tr> 
     <td>row 1, cell 1</td> 
     <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
     <td>row 2, cell 1</td> 
     <td>row 2, cell 2</td> 
    </tr> 
</table>​ 

Javascript

$('#tableID').click(function(e){ 
    alert($(e.target).text()); // using jQuery 
}) 
+3

Ha detto che vorrebbe usare javascript e non jquery. – RJo

+2

Grazie a @rjokelai, ha tag jQuery e ho perso quella parte della domanda. Ho aggiornato anche per javascript. – Adil

+0

grazie man ma intendo selezionare l'intera riga non solo il valore della cella, qualsiasi soluzione? – Luke

2
var table = document.getElementById('tableID'), 
    cells = table.getElementsByTagName('td'); 

for (var i=0,len=cells.length; i<len; i++){ 
    cells[i].onclick = function(){ 
     console.log(this.innerHTML); 
     /* if you know it's going to be numeric: 
     console.log(parseInt(this.innerHTML),10); 
     */ 
    } 
} 

from here

1

L'utilizzo di jQuery sarà facile ..

$("#tableId").find("td").click(function(event){ 
    var listOfCell=$(this).siblings(); 
    for(i=0;i<listOfCell.length;i++){ 
    alert($(listOfCell[i]).text()); 
} 
}); 
2

Spero che questo ti aiuta. Contiene script cross browser.

<html> 
    <head> 
    <script type="text/javascript"> 
    function myFun(e){ 
    if(!e.target) 
     alert(e.srcElement.innerHTML); 
    else 
     alert(e.target.innerHTML); 
    } 
    </script> 
    </head> 
    <body> 
    <table id="tableID" onclick="myFun(event)" border="1"> 
    <tr> 
    <td>row 1, cell 1</td> 
    <td>row 1, cell 2</td> 
    </tr> 
    <tr> 
    <td>row 2, cell 1</td> 
    <td>row 2, cell 2</td> 
    </tr> 
    </table> 
    </body> 
    </html> 
+0

grazie man è molto utile – Luke

Problemi correlati