如何获取使用JQuery单击的行的表格单元格

时间:2022-01-06 22:16:13

I have a table in HTML, and I have an onclick event for its rows.

我有一个HTML表格,我的行有一个onclick事件。

I was wondering if it was possible to find out which cell of the row was clicked, without having a seperate handler for each cell?

我想知道是否有可能找出该行的哪个单元格被点击,而没有为每个单元格分别处理?

I have a table:

我有一张桌子:

<tr class="new_row">
   <td class="date">date</td>
   <td class="name">name</td>
   <td class="delete">delete</td>
</tr>

and jquery:

$(".new_row").click(function(){
   if(delete was clicked){
       delete the row
   }
});

That is what I want to do basically, detect if the delete cell was clicked.

这就是我想要做的基本上,检测是否单击了删除单元格。

Is this possible?

这可能吗?

3 个解决方案

#1


1  

Look at the id of the event.target. If it matches delete, then you can process a delete.

查看event.target的id。如果它与删除匹配,则可以处理删除。

However, since this in a table, I'm guessing that you have multiple rows. If this is the case, does that mean that you have multiple cells with the same ID? If so, this isn't valid HTML and it could cause problems with your jQuery code, when you try to use CSS selectors.

但是,因为在表格中,我猜你有多行。如果是这种情况,这是否意味着您有多个具有相同ID的单元格?如果是这样,这是无效的HTML,当您尝试使用CSS选择器时,它可能会导致您的jQuery代码出现问题。

#2


5  

Firstly you should not define more than one element with same id, it will cause trouble, you can replace id='delete' with class='delete'.

首先,你不应该定义多个具有相同id的元素,这会导致麻烦,你可以用class ='delete'替换id ='delete'。

// on click td with class delete:
$("td.delete").click(function(){
   //delete was clicked so remove tr
   $(this).parent().remove();
});

#3


3  

You can do it like this

你可以这样做

Live Demo

$(".new_row").click(function(event){       
    if($(event.target).text() == 'delete')
    {       
      $(this).remove();      
    }
});

#1


1  

Look at the id of the event.target. If it matches delete, then you can process a delete.

查看event.target的id。如果它与删除匹配,则可以处理删除。

However, since this in a table, I'm guessing that you have multiple rows. If this is the case, does that mean that you have multiple cells with the same ID? If so, this isn't valid HTML and it could cause problems with your jQuery code, when you try to use CSS selectors.

但是,因为在表格中,我猜你有多行。如果是这种情况,这是否意味着您有多个具有相同ID的单元格?如果是这样,这是无效的HTML,当您尝试使用CSS选择器时,它可能会导致您的jQuery代码出现问题。

#2


5  

Firstly you should not define more than one element with same id, it will cause trouble, you can replace id='delete' with class='delete'.

首先,你不应该定义多个具有相同id的元素,这会导致麻烦,你可以用class ='delete'替换id ='delete'。

// on click td with class delete:
$("td.delete").click(function(){
   //delete was clicked so remove tr
   $(this).parent().remove();
});

#3


3  

You can do it like this

你可以这样做

Live Demo

$(".new_row").click(function(event){       
    if($(event.target).text() == 'delete')
    {       
      $(this).remove();      
    }
});