如何使用Javascript替换和附加

时间:2012-12-02 15:13:34

标签: javascript jquery replace append

我有一个评论系统,我希望在其中实现内联编辑(当有人知道一个好的插件或类似的东西时,请不要犹豫,给我一个名字)并找到一个Javascript片段,用以下内容替换文本textarea和text作为textarea的值。

但现在我需要在该textarea中添加一个按钮(提交按钮),以便用户可以保存他编辑的文本。

我的代码现在看起来像

<span id="name">comment</span>

<div onclick="replacetext();">test</div>

<script type="text/javascript">
    function replacetext(){
            $("#name").replaceWith($('<textarea>').attr({ id: 'name', value: $('#name').text() }));
    </script>

我已经使用$("#name").append('<button>yes</button>');对其进行了测试,但它没有用。

4 个答案:

答案 0 :(得分:2)

function replacetext() {

    $("#name").replaceWith($('<textarea>').attr({
        id: 'name',
        value: $('#name').text()
    }));
   $('#name').after('<button id="test">test</button>');
}

$('#test').live("click",function(){
   alert("I am a newly-created element and .click won't work on me.");

});

你不能在textarea中使用.append(),因为你不能“插入内容”或附加到它(还有其他的解决方法)。您可以在DIV,段落标记或任何可以作为容器的任何内容中执行此操作。

 http://api.jquery.com/append/
 http://api.jquery.com/after/
 http://api.jquery.com/live/或.on()http://api.jquery.com/on/

答案 1 :(得分:2)

可以使用以下jsFiddle尝试解决方案:http://jsfiddle.net/adb8X/5/

我相信你所追求的是:

  $('<button>yes</button>').insertAfter("#name");

上面的代码在目标选择器(“#name”)中具有指定id的DOM元素之后插入新创建的DOM元素(是)。

有关此insertAfter的更多信息:http://api.jquery.com/insertAfter/

如果您想将其插入replacetext(),它将变为:

function replacetext() {
    $("#name").replaceWith($('<textarea>').attr({
        id: 'name',
        value: $('#name').text()
    }));

    $('<button>yes</button>').insertAfter("#name");

} 

注意:我也纠正了你的jsFiddle。请在这里查看:http://jsfiddle.net/adb8X/5/(设置有问题,如果我没记错的话会有一个小错字)。相应的行是:

 $("#name").append( $('<button>hi</button>') );

答案 2 :(得分:1)

这是工作代码。

<span id="name">comment</span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<div onclick="replacetext();">test</div>

<script type="text/javascript">
    function replacetext(){
            $("#name").replaceWith($('<textarea>').attr({ id: 'name', value: $('#name').text() }));
            $('#name').after('<input type="submit" />');
    }
    </script>

如果有效,则接受它作为答案

答案 3 :(得分:1)

另一个选项可以让您替换动态生成的标签,而不仅仅是具有静态id =“Name”的标签,例如:

此示例中的标签或锚链接的html将替换为文本框:

<a href="#" onclick="editOpen(this);">@Html.DisplayFor(modelItem => Model.Name)</a>|

Javascript(editOpen函数内部)

function editOpen(ctrl) {
   //textbox
    var editText = $('<input>').attr({
        type: 'text',
        value: $(ctrl).text()
     });

    //edit button
    var saveEditLink = $('<input>').attr({value:'Save',type:'button'});

    //Put them together
    $(ctrl).replaceWith($(editText).after($(saveEditLink)));

}