如何在jQuery中将动态获取的ID传递给动态生成内容的删除按钮
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:
- In the Ajax
successcallback, use the clicked Save button ($(this)) to traverse up to its parent container (the dynamic.servor.serv__menu-titlediv you generated). - Locate the Delete button inside this container, then use
.attr()to set itsid-to-deleteattribute 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:
Then use<button class="mdl-button mdl-js-button js-delete-menu mdl-button--icon" id-to-delete=""> <i class="icon-delete"></i> </button>$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
相关产品推荐
相关产品推荐

