代码之家  ›  专栏  ›  技术社区  ›  Ari

动态编辑textarea文本后聚焦于textarea

  •  2
  • Ari  · 技术社区  · 6 年前

    我有一个textarea,每次检测到“keyup”时,它都会将textarea的当前值设置为textarea文本。原因是,这样这个文本就成为HTML的一部分,然后我可以使用localStorage保存输入的文本。

    到目前为止我的代码。。。

    $(document).on('keyup', '.note_text', function () {
        var text = $(this).val();
        $(this).text(text);
    });
    

    我使用$(document)将textarea动态创建到DOM中

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nico    6 年前

    添加此项,如中所述 jQuery documentation

    $("textarea").trigger("focus");

    如果不使用jQuery,则与以下内容相同:

    document.querySelector('textarea').focus();

    这两个例子都假设您的html只包含一个textarea。否则,您必须添加逻辑来选择正确的逻辑。

        2
  •  0
  •   Ari    6 年前

    经过反复试验,我终于找到了一个可行的解决办法。。。

     $(document).on('keyup', '.className', function () {
        var text = $(this).val(); // Gets the text of the textarea being typed in
        $(this).html(text); // Set the text as part of the html of the textarea
        $(this).focus(); // refocuses back on the text area so the user can type
        save(); // saves the DOM to the localStorage
    });