JQuery .clone() 和 .appendTo() 导致多次追加 [英] JQuery .clone() and .appendTo() causing multiple appends

查看:44
本文介绍了JQuery .clone() 和 .appendTo() 导致多次追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我阅读了许多类似的问题和答案 - 似乎没有一个解决这个特定问题.就这样吧.

考虑以下代码:

<脚本>函数 addAttendee() {$('.newAttendee').clone().appendTo('.attendees');}<form action="test2.php" name="testform" method="post"><span class="与会者"><input type="text" name="attendee[0][city]" value="city 1"><input type="text" name="attendee[0][state]" value="state 1"><input type="text" name="attendee[0][zip]" value="zip 1"></span><a href="#" name="addAttendee" onclick="addAttendee()">添加参加者</a><br><input type="submit" onclick="getOutput()"></表单><div class="hideThis" style="display: none;"><span class="newAttendee"><br><input type="text" name="attendee[1][city]" value="city 2"><input type="text" name="attendee[1][state]" value="state 2"><input type="text" name="attendee[1][zip]" value="zip 2"></span>

当我第一次点击添加参加者"时,我得到了我想要的.但是随后每次点击该链接都会导致插入之前插入的部分的两倍.第一次点击1,第二次点击2,第三次点击4,以此类推

我错过了什么吗?

提前致谢.

解决方案

因为 $('.newAttendee').clone() 将克隆所有具有该类的元素

尝试使用 first()last() 只克隆其中一个

$('.newAttendee').first().clone().appendTo('.attendees');

So I've read numerous similar questions and answers - none seem to address this specific issue. So here goes.

Consider the following code:

<body>
<script>

    function addAttendee() {
        $('.newAttendee').clone().appendTo('.attendees');
    }

</script>

<form action="test2.php" name="testform" method="post">
    <span class="attendees">
    <input type="text" name="attendee[0][city]" value="city 1">
    <input type="text" name="attendee[0][state]" value="state 1">
    <input type="text" name="attendee[0][zip]" value="zip 1">
    </span>
<a href="#" name="addAttendee" onclick="addAttendee()">Add Attendee</a>
<br>
<input type="submit" onclick="getOutput()">
</form>

<div class="hideThis" style="display: none;">
    <span class="newAttendee">
        <br>
    <input type="text" name="attendee[1][city]" value="city 2">
    <input type="text" name="attendee[1][state]" value="state 2">
    <input type="text" name="attendee[1][zip]" value="zip 2">
    </span>
</div>

When I click "Add Attendee" the first time, I get what I want. But each subsequent click on that link causes double the previous inserted sections to be inserted. First click 1, second 2, third 4, etc.

Am I missing something?

Thanks to all in advance.

解决方案

Because $('.newAttendee').clone() will clone all elements with that class

Try using first() or last() to only clone one of them

$('.newAttendee').first().clone().appendTo('.attendees');

这篇关于JQuery .clone() 和 .appendTo() 导致多次追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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