Javascript 具有相同id的按钮的jquery单击事件

Javascript 具有相同id的按钮的jquery单击事件,javascript,jquery,onclicklistener,Javascript,Jquery,Onclicklistener,我有一个这样的桌子结构 <table> <c forEach var="item" items="${manyItems}"> <tr> <td id="item1"> ${item.data1} </td> <td id="item2"> ${item.data2} </td> <td> <button id="deleteButton"/

我有一个这样的桌子结构

<table>
  <c forEach var="item" items="${manyItems}">
    <tr>
       <td id="item1"> ${item.data1} </td>
       <td id="item2"> ${item.data2} </td>
       <td> <button id="deleteButton"/> </td>
    </tr>
  </c:forEach>
</table>

${item.data1}
${item.data2}
现在我想在删除按钮中添加一个点击事件

在我的jquery中是这样的:

$(function() {
  $('#deleteButton').click(function() {
    var ele = $(this).parent();
    /* fetch the other <td> siblings of the #deleteButton */
    /* delete code goes here having an ajax query*/
  });
});
$(函数(){
$(“#删除按钮”)。单击(函数(){
var ele=$(this.parent();
/*获取#Delete按钮的其他同级*/
/*删除代码在这里有一个ajax查询*/
});
});
此代码仅删除表的第一行,但不适用于任何其他行

我相信这是因为我们需要有不同的id


请指导我找到一个好的解决方案。

您正在创建重复的ID,HTML中的标识符必须是唯一的,这是预期的行为

使用类,在下面的示例中,我已将
deleteButton
转换为CSS类,以便我们可以使用


问题是一个页面中多个元素的ID相同。当这种情况发生时,浏览器只会查找它的第一个实例,而不会继续查找另一个实例,这就是人们应该理解每个元素的ID应该是唯一的原因

改为更改为类名:

<table>
  <c forEach var="item" items="${manyItems}">
    <tr>
       <td class="item1"> ${item.data1} </td>
       <td class="item2"> ${item.data2} </td>
       <td> <button class="deleteButton"/> </td>
    </tr>
  </c:forEach>
</table>

${item.data1}
${item.data2}
和jquery:

$(function() {
  $('.deleteButton').click(function() {
    var ele = $(this).parent();
    /* fetch the other <td> siblings of the .deleteButton */
    /* delete code goes here having an ajax query*/
  });
});
$(函数(){
$('.deleteButton')。单击(函数(){
var ele=$(this.parent();
/*获取.deleteButton的其他同级*/
/*删除代码在这里有一个ajax查询*/
});
});

首先认为,
id
是已知唯一的,如果您需要两个
按钮的单击事件,您可以使用
class
选择
按钮,因此请尝试遵循标准,
id
是唯一的
selector
class
是多个
selector

不能在元素上具有相同的id如果“具有相同的id”失败,则没有这回事,它是无效的,而且您似乎已经知道它,那么为什么命名错误?
id
选择器返回第一个匹配的元素,而
class
选择器返回匹配元素的集合
<table>
  <c forEach var="item" items="${manyItems}">
    <tr>
       <td class="item1"> ${item.data1} </td>
       <td class="item2"> ${item.data2} </td>
       <td> <button class="deleteButton"/> </td>
    </tr>
  </c:forEach>
</table>
$(function() {
  $('.deleteButton').click(function() {
    var ele = $(this).parent();
    /* fetch the other <td> siblings of the .deleteButton */
    /* delete code goes here having an ajax query*/
  });
});