如何避免data-id从php循环返回表元素的相同id

我想使用 AJAX 更新记录,但是当我单击该edit行的按钮时,我得到的元素data-id与第一行相同。table


<table>

  <!-- this data inside php foreach loop displayed via ajax -->

  <tr>

    <td> <a href="<?= $row->id; ?>" id="edit_btn" data-id="<?= $row->id; ?>">edit</a></td>

    <td> <a href="<?= $row->id;?>'" id="delete_btn" data-id="<?= $row->id; ?>">delete</a></td>

  </tr>

</table>

$(function($) {

  edit();

})(jQuery);


function edit() {

  $(document).on('click', '#edit_btn', (e) => {

    e.preventDefault();

    var aid = $('#edit_btn').attr('data-id');

    // var aid = $('#edit_btn').data('id');

    alert(aid);

  });

}


狐的传说
浏览 138回答 3
3回答

胡说叔叔

您的代码中的主要问题是因为您将循环中的所有元素都赋予相同的id,这是无效的。id属性在 DOM 中必须是唯一的。您应该使用一个类来附加事件处理程序,然后在事件处理程序中使用this关键字来获取对引发事件的元素的引用。后一点意味着您需要删除箭头函数并改用匿名函数。话虽如此,您的代码中还有其他问题需要解决。首先,document.ready 事件处理程序不是 IIFE。从它的末端移除(jQuery)。此外,用于data()检索数据属性,而不是attr(). 最后,不要alert()用于调试,因为它会强制数据类型。改为使用console.log()。jQuery(function($) {&nbsp; edit();});function edit() {&nbsp; $(document).on('click', '.edit_btn', (e) => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; var aid = $(e.target).data('id');&nbsp; &nbsp; console.log(aid);&nbsp; });}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table>&nbsp; <!-- inside your loop ... -->&nbsp; <tr>&nbsp; &nbsp; <td><a href="#1" class="edit_btn" data-id="1">edit</a></td>&nbsp; &nbsp; <td><a href="#1" class="delete_btn" data-id="1">delete</a></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td><a href="#2" class="edit_btn" data-id="2">edit</a></td>&nbsp; &nbsp; <td><a href="#2" class="delete_btn" data-id="2">delete</a></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td><a href="#3" class="edit_btn" data-id="3">edit</a></td>&nbsp; &nbsp; <td><a href="#3" class="delete_btn" data-id="3">delete</a></td>&nbsp; </tr></table>如果您更喜欢使用箭头功能,那么this您需要使用e.target:$(document).on('click', '.edit_btn', (e) => {&nbsp; e.preventDefault();&nbsp; var aid = $(e.target).data('id');&nbsp; console.log(aid);});

慕桂英546537

您不能有多个具有相同 ID 的元素。jQuery 将始终使用找到的第一个。您可以为所有编辑/删除按钮设置一个类,并使用它来注册单击事件。您可以$(this)在回调内部使用来仅操作单击的元素<td><a class="edit_btn" data-id="<?= $row->id; ?>">edit</a></td><td><a class="delete_btn" data-id="<?= $row->id; ?>">delete</a></td>$(document).on('click','.edit_btn', function(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; var aid = $(this).data('id');&nbsp; &nbsp; alert(aid);});

阿波罗的战车

您应该使用data 方法检索数据 ID&nbsp;:var&nbsp;aid&nbsp;=&nbsp;$('#edit_btn').data('id');警告ID 必须是唯一的,特别是因为当您尝试与这些元素交互时,它会导致JavaScript和 CSS 出现问题。
打开App,查看更多内容
随时随地看视频慕课网APP