如何用 Javascript 替换和追加

2022-01-22 00:00:00 append replace jquery javascript

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

I have a comment system in which I want to realize inline-editing (when someone knows a good plugin or something similar please don't hesitate to give me a name) and found a Javascript snippet which replaces the text with a textarea and the text as the value of that textarea.

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

But now I need to add a button (submit button) to that textarea so that the user could save the text he edited.

我的代码现在看起来像

<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>'); 对其进行了测试,但没有成功.

I've tested it out with $("#name").append('<button>yes</button>'); but it didn't work.

推荐答案

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

The solution can be tried out using the following jsFiddle: http://jsfiddle.net/adb8X/5/

我相信你追求的是:

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

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

The code above inserts a newly created DOM element (yes) right after the DOM element with the specified id in the target selector ("#name").

更多关于 insertAfter 的信息在这里:http://api.jquery.com/插入后/

More about insertAfter here: http://api.jquery.com/insertAfter/

如果要插入到replacetext()中,会变成:

If you want to insert it into replacetext(), it will become:

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

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

} 

<小时>

注意:我还更正了您的 jsFiddle.请在此处查看:http://jsfiddle.net/adb8X/5/(存在问题如果我没记错的话,设置和一个小错字).其中对应的行是:


Note: I also corrected your jsFiddle. Please check here: http://jsfiddle.net/adb8X/5/ (There were problems with the settings and a small typo if I recall correctly). The corresponding line in that is:

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

相关文章