如何将点击的元素转换为textarea并返回?

时间:2016-11-11 15:47:29

标签: javascript jquery

根据this JSFIDDLE中找到的this SO answer,我基本上试图达到同样的目的,但是,我的元素不是div或者不能只是<p> } tag,可以基本上是任何元素,而下面的代码假设它将是<p>标记

我怎样才能让它回到原来的元素?

HTML

<p>If no background color...</p>
<span>Element shortcut method for ...</span>
<i>Element shortcut method which ...</i>

JS

    $(".modal-body div *").on("click", function(){
          divClicked();
    });
    function divClicked() {
        var divHtml = $(this).html();
        var editableText = $("<textarea />");
        editableText.val(divHtml);
        $(this).replaceWith(editableText);
        editableText.focus();
        // setup the blur event for this new textarea
        editableText.blur(editableTextBlurred);
    }

    function editableTextBlurred() {
        var html = $(this).val();
        var viewableText = $("<p>"); <-- Could have been another tag
        viewableText.html(html);
        $(this).replaceWith(viewableText);
        // setup the click event for this new div
        viewableText.click(divClicked);
    }

1 个答案:

答案 0 :(得分:1)

为什么你不能使用contenteditable =&#34; true&#34;你的div?

&#13;
&#13;
<div contenteditable="true">
  This text can be edited by the user.
</div>
&#13;
&#13;
&#13;

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content