我在想是否有一个更好的解决方案,为表格中的每个单元格添加onclick处理程序,而不是这种方法:将onclick事件添加到表格行
更好的方式是我不需要为每个单元格设置"cell.onclick = function".
我只需要获得用户点击的单元格的协调.
谢谢!
编辑:"协调"表示左上角单元格为0x0,第一行表示第二单元格为0x1等.
你在找这个吗?
$(function(){
$("#tableId tr td").click(function(event) {
alert(event.pageX);
alert(event.pageY);
});
});
Run Code Online (Sandbox Code Playgroud)
如果您的表格单元格是动态生成的:
$(function(){
$("#tableId tr td").live('click', function(event) {
alert(event.pageX);
alert(event.pageY);
});
});
Run Code Online (Sandbox Code Playgroud)
.
要获得top和left值,您可以尝试这样做:
$(function(){
$("#tableId tr td").click(function(event) {
alert($(this).offset().top);
alert($(this).offset().left);
});
});
Run Code Online (Sandbox Code Playgroud)
正如您的其他评论所示,您可能希望获取所单击单元格的ID,您可以尝试这样做:
$(function(){
$("#tableId tr td").click(function(event) {
alert($(this).attr('id'));
});
});
Run Code Online (Sandbox Code Playgroud)
但是为了使上述工作,假设所有单元已经具有id属性.