[英]How to delete a specific <li> of a particular <ul> from a list of several <ul>s
我的HTML页面中有10-15个无序列表,每个列表都包含每个列表项旁边的删除按钮。
为了使每个li具有唯一可识别性,我已将其分配给其id:其父ID和自己的category_name。
但是,当我执行remove()时 - 它不起作用。 li不会从其父级中删除。
我已经有一个与每个ul相关联的输入框,以便将li添加到特定的ul中,这是有效的。
<script>
function remove_category(ident){
$("#"+ident).remove;
}
function add_category(ul_id, input_id){
var ul = $("#"+ul_id);
var added_category = $("#"+input_id).val();
$(ul)
.append('<li class="list-group-item" id="'+added_category+'">'+added_category+'<button type="button" id="delete-category-btn" onclick="remove_category('+ul_id+added_category+');"><i class="fa fa-times delete-fa" aria-hidden="true"></i></button></li>')
}
</script>
remove_category()
函数不执行任何操作。
试着用这个,
function removeLi(dhis){ dhis.parent().remove() }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li >list 1 <button onclick="removeLi($(this))">remove</button></li> <li>list 2 <button onclick="removeLi($(this))">remove</button></li> <li >list 3 <button onclick="removeLi($(this))">remove</button></li> <li >list 4 <button onclick="removeLi($(this))">remove</button></li> <li >list 5 <button onclick="removeLi($(this))">remove</button></li> </ul>
可能是因为事件处理程序没有采用动态元素。 使用.on
使click事件在动态元素上起作用
这是一个例子。
$(document).on("click", ".added-category", function() { var parent = $(this).closest("li"); parent.after("<li>" + parent.html() + "</li>"); }); $(document).on("click", ".remove-category", function() { var parent = $(this).closest("li"); parent.remove(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li> some text <button class="added-category">Add</button> <button class="remove-category">Remove</button> </li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.