【问题标题】:Jquery clone and remove divJquery克隆并删除div
【发布时间】:2012-12-02 12:11:01
【问题描述】:

我已经实现了 jquery 克隆和删除。当点击 ADD 按钮时,带有某些表单元素的 DIV A 会被克隆并插入到另一个 DIV B 中。在 DIV A 中有一个隐藏的表单按钮 REMOVE。现在我需要在单击添加按钮时仅在克隆中启用删除按钮。 IE;我想让 DIV A 中的表单元素始终隐藏。

这是我的代码。

<div class="rule" id="rule">                        
            <div class="fm-req">
                <select name="rulefield" id="rulefield">
                    <option value="">select</option>
                </select>
            </div>
            <div class="fm-opt" >
                <input type="button" class='remove' value="-" style="display:none;"/>
            </div>
        </div>                  
    <div class="fm-rulebutton">
        <input type="button" id="addButton "class='add' value="+"/>
    </div>

        <div id='TextBoxesGroup' class="group">

这里 Div 'rule' 被克隆到 Div 'TextBoxesGroup'

$(document).ready(function() {
    var id = 0;
    $('.add').click(function(){
            id++;
            $('.fm-opt').children('.remove').show();
            var prot = $(document).find(".rule").clone();
            prot.attr("class", 'rule'+id)
            prot.find(".id").attr("value", id);

            $(document).find("div .group").append(prot);
    });        


    $('.remove').live("click", function(){
            $(this).closest("#rule").remove();
    });
});

【问题讨论】:

  • 我猜这行是指我们在您的代码中看不到的东西:prot.find(".id").attr("value", id);。我还看到您始终保持相同的 id 但更改班级,这是不正确的。 ID 应该是唯一的,而多个元素的 CLASS 可以是相同的。

标签: jquery html clone


【解决方案1】:

问题是您正在为所有删除按钮调用.show()。您需要将其限制为仅新的克隆元素。像这样:

$('.add').click(function(){
    id++;
    var prot = $(document).find(".rule").clone();
    prot.attr("class", 'rule'+id)
    prot.find(".id").attr("value", id);
    prot.find('input.remove').show();//<-- this is the important part

    $(document).find("div .group").append(prot);
});  

此代码现在只会在新克隆元素中找到的删除按钮上调用 .show()

【讨论】:

    【解决方案2】:
    $('.add').click(function(){
                id++;
                $('.fm-opt').children('.remove').show();
                var prot = $(document).find(".rule").clone();
                prot.attr("class", 'rule'+id)
                prot.find(".id").attr("value", id);
    
                $(document).find("div .group").append(prot);
        });   
    

    应该改成,

    $('.add').click(function(){
                id++;
                var prot = $(document).find(".rule").clone();
                prot.attr("class", 'rule'+id)
                prot.children('.remove').show();
                prot.find(".id").attr("value", id);
                $(document).find("div .group").append(prot);
        });   
    

    您应该只显示那些已克隆的按钮。

    【讨论】:

      【解决方案3】:

      克隆时为克隆的元素添加唯一的 Id="" 值。

      在 remove 方法中,您可以轻松访问唯一元素并将其删除。

      【讨论】:

      • 这不是问题所在。 OP想知道如何隐藏第一个元素中的“删除”按钮,并且只为克隆显示它(我认为)
      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 2012-05-07
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      相关资源
      最近更新 更多