admin管理员组

文章数量:1296509

I was thinking if there's a better solution for adding onclick handler to each cell in a table than this approach: Adding an onclick event to a table row

Better in the way that I wouldn't need to set "cell.onclick = function" for each cell.

I just need to get the coordinations of a cell where user clicked.

Thanks!

EDIT: The "coordinations" mean 0x0 for top-left cell, 0x1 for second cell in the first row etc.

I was thinking if there's a better solution for adding onclick handler to each cell in a table than this approach: Adding an onclick event to a table row

Better in the way that I wouldn't need to set "cell.onclick = function" for each cell.

I just need to get the coordinations of a cell where user clicked.

Thanks!

EDIT: The "coordinations" mean 0x0 for top-left cell, 0x1 for second cell in the first row etc.

Share edited May 23, 2017 at 12:01 CommunityBot 11 silver badge asked Apr 21, 2010 at 17:49 MartyIXMartyIX 28.7k32 gold badges139 silver badges217 bronze badges 1
  • 2 use JQuery and bind a function to the click event for all the <td>'s at once: $("td").live('click', function(){}); – dnagirl Commented Apr 21, 2010 at 17:52
Add a ment  | 

2 Answers 2

Reset to default 7

Are you looking for this?

$(function(){
    $("#tableId tr td").click(function(event) {
       alert(event.pageX);
       alert(event.pageY);
    });
});

In case your table cells are generated dynamically:

$(function(){
    $("#tableId tr td").live('click', function(event) {
       alert(event.pageX);
       alert(event.pageY);
    });
});

.

Update Based On OP Comment:

To get top and left values you could try this:

$(function(){
    $("#tableId tr td").click(function(event) {
       alert($(this).offset().top);
       alert($(this).offset().left);
    });
});

As your other ment shows, you are probably looking to get the IDs of the clicked cell, you may try this:

$(function(){
    $("#tableId tr td").click(function(event) {
       alert($(this).attr('id'));
    });
});

But for the above to work, it is assumed that all cells already have an id attribute.

You're looking for event delegation.

http://icant.co.uk/sandbox/eventdelegation/

among other examples. Basically observe some higher container such as the table for click events and then determine if you care to handle it by inspecting the event passed to the event handler.

So if the click happens inside the table, you can determine the target of the event and assuming there's a valid td present handle the event.

This has the benefit of allowing you to dynamically add more table cells without needing to add handlers to all of them.

jQuery in particular as an excellent delegate method for using this approach. http://api.jquery./delegate/

本文标签: How to hook onclick event for each cell in a table in JavascriptStack Overflow