【问题标题】:How can inner elements can be removed when cliking the button单击按钮时如何删除内部元素
【发布时间】:2015-04-16 14:17:46
【问题描述】:

在我的 html 中,我在一个 div 中有一个 div 列表,每个 div 都有复选框[input type=checkbox]。

我的目标是当我选中复选框并选择删除按钮时,必须删除父 div(输入的父项:复选框),我试过了,但是我做不到。有什么帮助吗?

$("#delbtn").click(function(e) {
    var divLen=$("#checkbox-content div");

    for(var k=0;k<divLen.length;k++)
    {
        if(divLen[k].children("input").attr("checked")){
            divLen[k].remove();
        }
    }
    return false;
});

HTML

<div id="checkbox-content">
    <div><input type="checkbox" name="checkedvalue"/>Some text</div>
    <div><input type="checkbox" name="checkedvalue"/>Some text</div>
    <div><input type="checkbox" name="checkedvalue"/>Some text</div>
</div>
<button id="delbtn">Remove</button>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    试试这个:删除选中复选框的 div

    $("#delbtn").click(function(e) {
        $("#checkbox-content div").has(':checkbox:checked').remove();
     });
    

    JSFiddle Demo

    【讨论】:

      【解决方案2】:

      只需获取选中的复选框,引用其父级,然后将其删除。不错的简单选择器 + 1 个衬里。

      $('#checkbox-content :checkbox:checked').parent().remove();
      

      如果“checkbox-content”只包含复选框,甚至更小的行:

      $('#checkbox-content :checked').parent().remove();
      

      【讨论】:

        【解决方案3】:

        单击按钮时,检查哪些复选框被选中,并删除其父元素及其内容。

        检查以下代码:

        $(document).on('click', '#delbtn', function() {
          $('#checkbox-content input[type=checkbox]').each(function() {
            var that = $(this);
            if (that.is(':checked')) {
               that.closest('div').remove();
            }
          });
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <div id="checkbox-content">
                    <div><input type="checkbox" name="checkedvalue"/>Some text one</div>
                    <div><input type="checkbox" name="checkedvalue"/>Some text two</div>
        <div><input type="checkbox" name="checkedvalue"/>Some text three</div>
                    </div>
                    <button id="delbtn">Remove</button>

        【讨论】:

        • 这可以大大简化。 jQuery 选择器提供了您在没有循环或条件的情况下执行该逻辑所需的一切。
        猜你喜欢
        • 2021-10-12
        • 2021-05-14
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多