How to hook onclick event for each cell in a table in Javascript?
I was thinking if there's a better solution fo开发者_开发百科r 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.
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 comment 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.com/delegate/
精彩评论