获得textarea的价值后克隆一次

时间:2012-11-28 23:43:20

标签: javascript jquery html jquery-ui

我基本上有这个http://jsfiddle.net/NgEpS/1/,我在每个表单上得到textarea的值,并将值附加到子div,一切都正常。在第一次提交后完成。但是如果你提交的不止一次同样的表格,我的脚本正在克隆所有以前的回复,想知道​​是否有办法避免这种情况。

HTML:

        <div class="post-container">
            <form class="reply-form">
                <div class="reply-box">
                    <textarea placeholder="Reply box 1..." columns="10" rows="1" name="comment-input"></textarea>
                    <input type="submit" value="Send">
                </div>
                <div class="post-dropdown"></div>
                <div class="post-dropdown-content">
                    <div class="post-dropdown-reply">1</div>
                </div>
            </form>
        </div>

        <div class="post-container">
            <form class="reply-form">
                <div class="reply-box">
                    <textarea placeholder="Reply box 2..." columns="10" rows="1" name="comment-input"></textarea>
                    <input type="submit" value="Send">
                </div>
                <div class="post-dropdown"></div>
                <div class="post-dropdown-content">
                    <div class="post-dropdown-reply hidden"></div>
                </div>
            </form>
        </div>

        <div class="post-container">
            <form class="reply-form">
                <div class="reply-box">
                    <textarea placeholder="Reply box 3..." columns="10" rows="1" name="comment-input"></textarea>
                    <input type="submit" value="Send">
                </div>
                <div class="post-dropdown"></div>
                <div class="post-dropdown-content">
                    <div class="post-dropdown-reply">1</div>
                    <div class="post-dropdown-reply">2</div>
                    <div class="post-dropdown-reply">3</div>
                    <div class="post-dropdown-reply">4</div>
                </div>
            </form>
        </div>
        p​

JavaScript的:

        function gettingReplyVal() {

            $('.reply-form').submit(function(e) {
                var post_clone =    $('.post-dropdown-content').first().clone();

                var textAreaValue = $(this).find('textarea').val();

                 $(post_clone).insertBefore($(this).f ind(".post-dropdown-content")).find('.post-dropdown-reply').html(textAreaValue); 

                e.preventDefault();

            });
        }

        gettingReplyVal();

1 个答案:

答案 0 :(得分:1)

在这一行

$(post_clone).insertBefore($(this).find(".post-dropdown-content")).find('.post-dropdown-reply').html(textAreaValue); 

$(this).find(".post-dropdown-content")会返回this内的所有post-dropdown-content元素。你第一次点击发送,只有一个,所以它表现正常,但第二次发现两个,第三次发现三个等等......

使用$(this).find(".post-dropdown-content").first()代替

$(post_clone).insertBefore($(this).find(".post-dropdown-content").first()).find('.post-dropdown-reply').html(textAreaValue);