1

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

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

这是例如我的html:

编辑按钮
<li>
    <p><strong>Phone number:</strong><span class="editable">Some text which can be edited.</span>
</li>

我的 jQuery 代码:

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

1 回答 1

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);
        });
    }
});

查看演示

于 2013-05-29T13:25:17.790 回答