每次单击链接以克隆html时,jQuery的克隆量都会增加一倍? [英] jQuery is doubling my cloning everytime I click a link to clone html?

查看:87
本文介绍了每次单击链接以克隆html时,jQuery的克隆量都会增加一倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下html片段包含输入,选择和链接.当我单击链接时,我想基本上克隆行,我希望将新行追加到最后一行.我也希望删除链接并将其添加到最后一行.我也想把偶数结转下来.我将把我的jquery代码放在html下面.

The following html snippet contains an input, a select and a link. When I click the link, I want to basically clone line, I want the new line to be appended to the last line. I also would like the link to be removed and be added to the last line. I want to have the even carried over as well. I will put my jquery code below the html.

<div id="lines">
    <div class="line">
        <span>Value</span><input type="text" name="value" class="value"/>
        <span>Type</span>
        <select name="type" class="type">
        <option>$</option>
    <option>%</option>
    </select>
        <a id="addLine" href="#">Add</a>
    </div>
</div>

$(document).ready(function() {
$('#addLine').click(function() {

       $('.line').clone({withDataAndEvents:true}).appendTo('#lines');

    });
});

当我单击添加时,它首先在第一行的下面添加第二行,但是当我再次单击添加时,它添加了2行,所以我有4行,每次单击添加时,它使行数加倍这是我所不想要的.我也想从除最后一行以外的所有行中删除.我可能还会有一个Remove来删除特定的行,所以我想提出有关如何处理此行的建议.

When I click add, it first adds a second line below the first one, but then when I click add again, it adds 2 lines, so I have 4, every time I click add, it is doubling the amount of lines which is what I don't want. I also want add removed from all the lines except the last one. I probably will have a Remove as well to remove a specific line, so I would like suggestions on how to handle this.

推荐答案

这是因为您正在使用line类克隆整个元素集,这意味着第一次添加一行,第二次添加一行,因此第三将添加4.您可以通过使用.last克隆一行来解决此问题:

That's because you're cloning the whole element set with the line class, meaning the first time it adds one line, the second will add 2, the third will add 4. You can fix this by just cloning one line with .last:

$('#addLine').click(function() {
    $('.line').last().clone({
        withDataAndEvents: true
    }).appendTo('#lines');
});

这篇关于每次单击链接以克隆html时,jQuery的克隆量都会增加一倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆