【问题标题】:Focusing on a textarea after dynamically editing textarea text动态编辑 textarea 文本后关注 textarea
【发布时间】:2018-10-02 03:29:48
【问题描述】:

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

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

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

我的问题是,一旦检测到 keyup,文本区域就不再是焦点,所以你必须重新点击它并再次输入,显然你只能按住键来连续输入,就像你输入一样通常该功能是由向上键触发的。

我正在使用 $(document),因为 textarea 是动态创建到 DOM 中的

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    添加这个,如jQuery documentation中所述:

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

    如果没有 jQuery,这将与以下内容相同:

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

    这两个示例都假设您的 html 仅包含一个文本区域。否则你必须添加逻辑来选择正确的。

    【讨论】:

    • 我有多个文本区域。逻辑复杂吗?我添加了一个计数器变量,每次添加新的文本区域时都会增加 1,并且该数字设置在文本区域“id”处,例如。如果添加了三个文本区域,它们将是 id='1' id='2', id='3'。如果添加更多,依此类推。
    • 可以将页面上的所有textarea作为一个数组获取,然后通过索引到数组中获取相关的。例如,获取第 3 个文本区域:document.querySelectorAll("textarea")[2]
    【解决方案2】:

    经过反复试验,我设法找到了一个可行的解决方案......

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 2012-10-14
      相关资源
      最近更新 更多