当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Get id of table cell

问题描述:

I've got a html-table that is actually a chessboard. Something like:

<table id="chessboard">

<tr>

<td id="A8"></td>

<td id="B8"></td>

<td id="C8"></td>

<tr>

<tr>

<td id="A7"></td>

<td id="B7"></td>

<td id="C7"></td>

<tr>

<tr>

<td id="A6"></td>

<td id="B6"></td>

<td id="C6"></td>

<tr>

</table>

Now I am trying to make a JQuery script that returns the cell id (ie "A8", "B6", etc) once one clickes anywhere on in the table (chessboard). I've tried a lot, but I can't get it to work.

One of the things I tried:

$("#chessboard").on("click", function(cell){

alert(cell.target).attr("id"));

})

Anybody got a solution?

网友答案:

Try:

$("#chessboard td").on("click", function(cell){
    alert(this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="chessboard">
    <tr>
       <td id="A8">A8</td>
       <td id="B8">B8</td>
       <td id="C8">C8</td>
    <tr>
    <tr>
       <td id="A7">A7</td>
       <td id="B7">B7</td>
       <td id="C7">C7</td>
    <tr>
    <tr>
       <td id="A6">A6</td>
       <td id="B6">B6</td>
       <td id="C6">C6</td>
    <tr>
</table>
网友答案:

cell.target in this case refers to the DOM element that dispatched the event. DOM elements don't have a .attr() method, that is a jQuery object method.

To use it, you'd need to first wrap up your DOM element in a jQuery object:

$("#chessboard").on("click", function(e){
    $cell = $(e.target);
    alert($cell.attr('id'));
});

Nitpick: Call the event something relevant, not cell. It'll just confuse you later on.

网友答案:

Try something like...

    $('#chessboard').click(function() {
    alert($(this).attr('id'));
});

The 'this' works like a charm.

Also don't forget to reference the jquery script somewhere in your document:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
网友答案:

Try this mate

  $("#chessboard tr").on("click","td", function(cell){
        alert(this.id);
    })

this is the example on JSFIDDLE

网友答案:

Thanks for the replies. I've got the answer.

This worked:

$("#chessboard td").on("click", function(cell){
    alert(this.id);
})
分享给朋友:
您可能感兴趣的文章:
随机阅读: