LoginSignup
1
2

More than 5 years have passed since last update.

jQueryでタグを入れ替える例(p ⇔ textarea)

Posted at

要件

・p要素の時クリックするとtextareaに
・textareaの時にblurするとpに

コード

<div class="container">
<p class="text js-click"></p>
</div>
$(document).ready(function () {
    // p要素の時クリックすると編集出来るtextareaになる
    $('div.container').on('click', 'p.js-click',function () {
        $(this).replaceWith(function () {
            $(this).replaceWith("<textarea class=\"text js-click-term\">" + $(this).text() + "</textarea>");
        });
        // ここでfocusしないと、次のblurイベントが起きない
        $('textarea.js-click-term').focus();
    });
    // textareaの時フォーカスを外すとp要素に戻る
    $('div.container').on('blur', 'textarea.js-click',function () {
        $(this).replaceWith(function () {
            $(this).replaceWith("<p class=\"text js-click\">" + $(this).text() + "</p>");
        });
    });
});

補足

このコードだと、textareaで編集した内容はpに戻った時に反映されないのでVueのv-modelとかでやると楽そう。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2