5

我正在尝试使用 jquery 克隆具有类“.age-sex-details”的 html div 元素以及绑定到下面显示的“.age-sex-remove”和“.age-sex-add”类的事件 clone函数克隆具有类“.age-sex-details”的 html div 元素以及绑定到下面显示的“.age-sex-remove”和“.age-sex-add”类的事件. 我可以使用 .clone(true) 函数克隆 div、上面提到的事件和输入到输入框中的数据,但是我需要克隆 div 元素和提到的事件,而不是在“计数”中输入的数据和“年龄”输入字段。这可能吗?

代码简要说明

下面的 jQuery 代码由文档就绪函数中的两个函数组成。你可以忽略第一个。第二个功能是我进行克隆的地方。我克隆了下面 HTML 中显示的 div 元素,并将其插入到自身之后。

查询代码

$(document).ready(function() {
        $(".age-sex-remove").click(function() {
            var index = $(".age-sex-details").length;
            if ( index > 1) {
                $(this).parent().remove();
                $($(".age-sex-add")[index - 2]).show();
            } else {
                console.log("only one set of age sex details, therefore clear values.")
            }
        });

        /**
         * Clone age-sex-details div including events and excluding data.
         * Hide the previous add new sex age details link.
         */
        $(".age-sex-add").click(function() {
            var index = $(".age-sex-details").length;
            console.log("Index = " +index);
            $($(".age-sex-details")[index - 1]).clone(true).insertAfter($(".age-sex-details")[index - 1]);
            $($(".age-sex-add")[index - 1]).hide();
        });
    });

HTML

<div class="form-inline age-sex-details">
    <div class="form-group">
        <label for="Count">Count</label>
        <input type="text" name="count" class="form-control" id="Count" />
    </div>    
    <div class="form-group">
        <label for="Age">Age</label>
        <input type="text" name="age" class="form-control" id="Age" />
    </div>    
    <div class="form-group">
        <label for="Sex">Sex</label>
        <select name="sex" class="form-control" id="Sex">
            <option value="0">Female</option>
            <option value="1">Male</option>
        </select>
    </div>    
    <a href="#" class="glyphicon glyphicon-remove age-sex-remove">&nbsp;</a>
    <a href="#" class="glyphicon glyphicon-plus age-sex-add">&nbsp;</a>
</div>

这是代码的JSFiddle

谢谢,优素福

4

2 回答 2

7

克隆元素后,您可以不带参数调用removeData() :

var cloneWithEventsOnly = $("selector").clone(true).removeData();

编辑:clone()看起来您想清除表单控件值(根据的文档,不应首先复制,但显然是)。

在这种情况下,您可以使用:input选择器匹配表单控件并使用val()清除它们的值:

var cloneWithoutValues = $("selector").clone(true).find(":input").val("").end();

或者,在您的特定情况下:

var source = $(".age-sex-details").eq(index - 1);
source.clone(true).find(":input").val("").end().insertAfter(source);
于 2014-01-10T21:19:19.647 回答
1
 var data = $($(".age-sex-details")[index - 1]).clone(true);
 $(data).find(':input').val("");;
 $(datal).insertAfter($(".age-sex-details")[index - 1]);
于 2014-01-10T22:13:20.597 回答