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

JavaScript Delete函数无法正常运行,请求技术排查解决

Troubleshooting Your Non-Working Delete Function

Hey there! Let’s figure out why your Delete function isn’t behaving as expected. Looking at the code snippets you shared, the biggest red flag here is that you’re dynamically adding elements (like exercise blocks via getExerciseBlock(id)), which is the most common reason for event handlers failing with dynamic content.

Here are the key issues to check and fix:

1. Your Delete Event is Only Bound to Initial DOM Elements

Regular .on('click', ...) bindings only attach to elements that exist when the page first loads. When you add new exercise blocks later (via the "Add" button), those new Delete buttons won’t have the click event attached to them.

Fix: Use Event Delegation

Instead of binding directly to the Delete button, bind the event to a static parent element that exists on page load (like .panel-body), and target the Delete button as a child. This way, any future Delete buttons added to that parent will inherit the event.

Example code:

$(document).ready(function(){
    var id = 0;
    var addOpdracht = $('<a/>', { 
        'class': 'btn btn-success', 
        'id': 'addOpdracht' 
    }).on('click', function(){
        $('.panel-body').append(getExerciseBlock(id)); 
        id++; 
    }).html('<i class="fa fa-plus"></i>'); 
    $('.jumbotron').append(addOpdracht);

    // Event delegation for Delete buttons
    $('.panel-body').on('click', '.delete-btn', function() {
        // Replace with your actual Delete logic
        // For example, remove the parent exercise block
        $(this).closest('.exercise-block').remove();
    });
})

// Make sure your getExerciseBlock returns a Delete button with the correct class
function getExerciseBlock(id) {
    return `
        <div class="exercise-block" data-id="${id}">
            <!-- Your exercise content here -->
            <a class="btn btn-danger delete-btn">
                <i class="fa fa-trash"></i> Delete
            </a>
        </div>
    `;
}

2. Missing or Incorrect Delete Button Binding

From your code snippet, you didn’t include the actual Delete function binding. Double-check:

  • Did you forget to write the event handler for the Delete button entirely?
  • Are you using the correct selector (class/id) for the Delete button in your binding?
  • Is the Delete button actually being rendered in the HTML returned by getExerciseBlock(id)?

3. Potential ID Conflicts

You’re using an incrementing id variable to generate blocks, but if your Delete logic relies on matching this ID to the button, make sure the ID is correctly attached to both the block and the Delete button (e.g., using a data-id attribute as in the example above).


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:48:46