0

I'm having some weird behavior with appendTo() in jQuery.

This is my JS:

$(document).ready(function() {
    $("a#mydiv").click(function () {
        $(this).append('<div class="well">Added div</div>' );
        $(this).appendTo(div.last);
    });
});

And my HTML:

<div id="last">
    <center><a id="mydiv"><h3>New List</h3></a></center>
</div>

Obviously, when I click the "New List" link, I get a new <div> added to <div id="last">. It looks like this:

Picture of divs

And if I keeping clicking New List, I get more and more <div>s. This is fine. However, when I click one of the newly-create <div>s, it also adds one. (WHen I click the "added div" grey space). I;m going to be putting textboxes in these new <div>s, and I don't want it adding more and more <div>s when the user clicks to type.

What can I do to make it so new <div>s are created only when I click the "New List" link?

Thanks!

4

2 回答 2

4

使用.after()而不是.append(). 目前,您的新 div 已添加到您的 a 标记中。

于 2012-08-09T14:55:56.640 回答
1

那是因为append()添加了一个孩子,而不是兄弟姐妹。所以点击指的是整个容器myDiv,其中包含所有添加的 div 并保持可点击状态。用于after()添加同级。

于 2012-08-09T14:57:09.710 回答