JQuery .clone() and .appendTo() causing multiple appends

蓝咒 提交于 2020-01-25 04:05:50

问题


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.


回答1:


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');



回答2:


This is because $('.newAttendee') select all elments with class newAttendee. And after you clone it you have 2 and so on. Changing the class after cloning would avoid this.



来源:https://stackoverflow.com/questions/36103849/jquery-clone-and-appendto-causing-multiple-appends

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!