输入 HTML 的输入值,而不是 DOM

enter value of input to the html, not the dom

本文关键字:输入 DOM HTML      更新时间:2023-09-26

我的html文件中有一个输入(属性id是:imgName)。

当用户在此输入中输入一些文本时,它会插入到 DOM 中。

我希望将其插入到html中。

所以我尝试做这件事:

$(document).keydown(function (e) {
    if (e.target.id == "imgName") {
        // get the char and create text node
        var text = document.createTextNode(String.fromCharCode(e.which));
        // insert it to the input
        e.target.appendChild(text);
    }
});

但它什么也没做..

任何帮助表示赞赏!

你做错了什么:

  1. 您正在侦听整个文档上的输入事件,但您的输入将只在输入字段上。 所以你需要: $('#imgName').keydown...

  2. 您正在使用jQuery...因此,使用它来做这些事情更容易。

  3. 不需要您的条件。

试试这个:

$('body').append(String.fromCharCode(e.which));

演示

您不能将某些内容附加到输入中,它是一个没有内容的自闭合元素,要从String.fromCharCode中获得正确的结果,您应该使用 keypress 事件

$('#imgName').on('keypress', function (e) {
    var text = document.createTextNode(String.fromCharCode(e.which));
    document.body.appendChild(text);
});

小提琴