You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery中将动态获取的ID传递给动态生成内容的删除按钮

How to pass the saved ID to the corresponding Delete button in dynamically generated content

The key issue here is avoiding global variables to store the returned ID—when you generate multiple dynamic divs, the global variable will get overwritten by subsequent requests, leading to incorrect IDs on Delete buttons. The right approach is to directly target the Delete button within the same dynamic div as the clicked Save button in your Ajax success callback, then assign the returned ID to its id-to-delete attribute.

Fixed Implementation Steps:

  1. In the Ajax success callback, use the clicked Save button ($(this)) to traverse up to its parent container (the dynamic .serv or .serv__menu-title div you generated).
  2. Locate the Delete button inside this container, then use .attr() to set its id-to-delete attribute with the database returned ID (data).

Modified Save Button Ajax Code:

$(document.body).on('click', 'button.js-save', function () {
  const $saveBtn = $(this); // Store reference to the clicked Save button
  const $currentServDiv = $saveBtn.closest('.serv'); // Get the parent dynamic div
  const name = $currentServDiv.find('input[type="text"]').val();
  const datatoInsert = { name: name };
  
  $.ajax({
    type: 'POST',
    url: '@Url.Action("SaveDetails", "MainMenu")',
    data: { valDetails: JSON.stringify(datatoInsert) },
    success: function (data) {
      alert('Value saved');
      // Target the Delete button in the same div and set its ID attribute
      $currentServDiv.find('button.delete-menu-').attr('id-to-delete', data);
    },
    error: function () {
      console.log('Error');
    }
  });
});

Extra Optimization Tips:

  • Give your Delete button a more specific class (like js-delete-menu) to make targeting more reliable and avoid conflicts. Update your dynamic div template:
    <button class="mdl-button mdl-js-button js-delete-menu mdl-button--icon" id-to-delete="">
      <i class="icon-delete"></i>
    </button>
    
    Then use $currentServDiv.find('button.js-delete-menu') in the success callback for clearer, safer selection.
  • Consider disabling or hiding the Save button after a successful submission to prevent duplicate requests and improve user experience.

This way, each dynamically generated div's Delete button will get its own corresponding saved ID, with no cross-interference between different divs.

内容的提问来源于stack exchange,提问作者crazydev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:36:47