简体   繁体   English

使用jQuery删除动态生成的HTML

[英]Removing dynamically generated html with jQuery

I want to remove dynamically generated '.row' but it is possible only for the static one. 我想删除动态生成的“ .row”,但只能用于静态的。 Second row is generated dynamically. 第二行是动态生成的。

I wanted to provide image but I have not enough reputation. 我想提供图像,但声誉不高。 Here are my code snippets: 这是我的代码段:
1. Static '.row' 1.静态“ .row”

        <div class="col-sm-4" style="padding-left: 0;">
            <select>
                <option value="">Skill Level</option>
                <option value="">1</option>
                <option value="">2</option>
                <option value="">3</option>
            </select>
        </div>
        <div class="col-sm-2" style="padding-left: 0;">
            <div class="delete-myskill-candidate progress-bar-candidate toggle">
                <a class="progress-bar-candidate-toggle">-</a>
            </div>
        </div>
    </div>
</div>

2. Code for removing '.row'. 2.删除“ .row”的代码。 Works fine for static row but it can't remove dynamically generated rows. 对于静态行工作正常,但不能删除动态生成的行。

$('.delete-myskill-candidate').on('click', function (events) {     
    $(this).closest(".row").remove();  
});

3. Rows are generated based on static one and jQuery append(). 3.行是基于static one和jQuery append()生成的。

$("#mySkills").append(firstDiv.append(selectList).append(deleteButton));

firstDiv, selectList and deleteButton are same as in HTML. firstDiv,selectList和deleteButton与HTML中的相同。

I think that dynamically generated content need some kind of 'binding' but I don't have a clue how to achieve that. 我认为动态生成的内容需要某种“绑定”,但是我不知道如何实现。 Any suggestions? 有什么建议么?

Use delegated events. 使用委托事件。

Direct and delegated events 直接事件和委托事件

Event handlers are bound only to the currently selected elements; 事件处理程序仅绑定到当前选定的元素; they must exist at the time your code makes the call to .on() . 它们必须在您的代码调用.on()时存在 To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. 为确保元素存在并可以选择,请将脚本放在HTML标记中的元素之后,或在文档就绪处理程序内执行事件绑定。 Alternatively, use delegated events to attach event handlers. 或者,使用委托事件来附加事件处理程序。

Just change the click handler from 只需更改点击处理程序即可

$('.delete-myskill-candidate').on('click', function (events) {     
    $(this).closest(".row").remove();  
});

to

$('selector of upper most parent').on('click', '.delete-myskill-candidate', function (events) {     
    $(this).closest(".row").remove();  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM