开发者

Figure out which row in an HTML table was clicked [duplicate]

开发者 https://www.devze.com 2023-04-08 05:47 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to detect which row [ tr ] is clicked?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to detect which row [ tr ] is clicked?

I have a table like this:

<table>
   <tr>
      <td>1</td><td>1</td><td>1</td>
   </tr>
   <tr>
      <td>2&l开发者_C百科t;/td><td>2</td><td>2</td>
   </tr>
   <tr>
      <td>3</td><td>3</td><td>3</td>
   </tr>
</table>

In JavaScript (no jQuery please) how do I work out if a user clicks on the table on which row he/she clicked?


event.target, getElementsByTagName, traditional event method:

var trs = document.getElementsByTagName('tr');

for (var i = 0; i < trs.length; i++) {
     trs[i].onclick = clickHandler;   
}

function clickHandler(event) {
    alert(this.innerText || this.textContent);  // edit: textContent for firefox support
}

jsFiddle


function handleEvent(e) {
  // Do stuff with the row
}

var rows = document.getElementsByTagName('tr');
for (var row in rows) {
  row.addEventListener('click', handleEvent); 
  // or attachEvent, depends on browser
}


If you attach a click event handler to the table, you can get the event target, which will contain the element that was actually clicked:

document.getElementById("yourTable").onclick = function(e) {
    console.log(e.target);   
}

In your example, that's likely to be a td, so you could access the tr like this:

var tr = e.target.parentNode;

You can check the type of element that has been clicked with the tagName property:

var clickedElementType = e.target.tagName; //Returns something like "TD"

Alternatively, you could iterate over all the tr elements in your table and bind a click event handler to each.


window.onload = function(){
  var table = document.getElementById('myTableID');
  table.addEventListener('click',test,false);
}

function test(e){
  var element = e.srcElement || e.target;
  if(element.nodeName == 'TABLE') return;

  while(element.nodeName != 'TR') element = element.parentNode;
  alert(element.rowIndex);
}


I prefer to attach an event to the DOM element vs setting onclick. You'll have to do some checking if you want it to work with IE:

var trs = document.getElementsByTagName('tr');
var len = trs.length

var clickHandler = function(i){
    alert('clicked');
};

for(var i = 0; i < len; i++){
    var theRow = trs[i];

    if(theRow.addEventListener){
        theRow.addEventListener('click',clickHandler);
    }
    else{
        theRow.attachEvent('onclick',clickHandler);
    }
}


Add an id to each row and then you can query the node id from the Javascript onclick() handler


How about putting an onClick on the <tr>?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号