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
2 Answers
Reset to default 7Are 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
版权声明:本文标题:How to hook onclick event for each cell in a table in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741628291a2389207.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论