jQuery用值替换元素以输入

Rob*_*ert 1 jquery edit button

我正在处理一个编辑按钮,当我单击该按钮时,我可以通过输入字段编辑页面中的某些元素。因此,如果我单击具有 .editable 类的元素,则必须将其更改为输入字段,并且该值必须是元素中的文本。当我再次单击保存(编辑)按钮时,必须将值更改为新值。

(我知道我必须将新数据保存在数据库中,但这并不重要。此页面的工作方式类似于编辑按钮必须如何工作的示例)。

这是例如我的 html:

编辑按钮
<li>
    <p><strong>Phone number:</strong><span class="editable">Some text which can be edited.</span>
</li>
Run Code Online (Sandbox Code Playgroud)

我的jQuery代码:

$("#edit").click(
   function() {
      $("#edit").text('Save');
      $(document).find('.editable').each(function() {
         $(this).replaceWith("<input>");
      });
});
Run Code Online (Sandbox Code Playgroud)

tec*_*bar 5

尝试这个:

$("#edit").click(function() {
    var $this = $(this);
    if($this.attr('editing') != '1') {
        $this.text('Save').attr('editing', 1);
        $(document).find('.editable').each(function() {
            var input = $('<input class="editing" />').val($(this).text());
            $(this).replaceWith(input);
        });
    }
    else {
        $this.text('Edit').removeAttr('editing');
        $(document).find('input.editing').each(function() {
            var div = $('<div class="editable" />').text($(this).val());
            $(this).replaceWith(div);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

观看演示