单击时将div中的文本添加到textarea

时间:2014-07-16 14:25:26

标签: javascript jquery html

我想允许用户编辑他们的帖子,为了做到这一点我希望他们能够点击一个链接,一旦按下他们的帖子原来会隐藏的div,并且可以看到一个新的div来自textarea里面的旧div的文本 - 所以他们可以轻松地编辑他们的旧帖子。

我已经尝试搜索过去一小时,无法在任何地方找到可靠的答案。

我的HTML:

<div class="post-content">
    <div class="post-inner-content">
        <p>Users comment will go here</p>
    </div><!-- .post-inner-content -->
    <a href="#" class="edit-post">Edit Post</a>
    <div class="edit-post-area">
        <textarea></textarea>
    </div><!-- .edit-post-area -->
</div><!-- .post-content -->

3 个答案:

答案 0 :(得分:2)

应该很简单:

$("a.edit-post").click(function() {
    //Get the text
    var text = $(this).prev("div.post-inner-content").text();

    //Create a text area selector (container, rather)
    var textarea = $(this).next("div.edit-post-area");

    //Give the textarea a value
    $("textarea", textarea).val(text);

    //Show it (if hidden)
    //textarea.show();
});

小提琴:http://jsfiddle.net/tudcP/

答案 1 :(得分:0)

替代方案你可以使用它:

<强> JS

$(".edit-post").on("click", 
               function(){                      
                   var edit = $(this)
                   .prev()
                   .find("p")
                   .html();//find comment to edit

                    $(this)
                    .next()
                    .find("textarea")
                    .val(edit);//find textarea and insert comments to edit                                        
               });

fiddle

答案 2 :(得分:0)

使用ID代替类并以这种方式选择它们:

<div class="post-content">
    <div id="post-inner-content">
        <p>Users comment will go here</p>
    </div><!-- .post-inner-content -->
    <a href="#" id="edit-post">Edit Post</a>
    <div id="edit-post-area">
        <textarea></textarea>
    </div><!-- .edit-post-area -->
</div>

JavaScript的:

$("#edit-post").click(function() {
    //Get the text
    var text = $("#post-inner-content").text()

    //Create a text area selector (container, rather)
    var textarea = $("#edit-post-area");

    //Give the textarea a value
    $("textarea", textarea).val(text);

    //Show it
    textarea.show();
});

Fiddle

相关问题