2014-03-31 24 views
0

我在我的html文件中输入了一个输入(属性id是:imgName)。将输入值输入到html,而不是dom

当用户输入一些文本到这个输入时,它被插入到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
String.fromCharCode得到正确的结果

你做错了什么:

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

  2. 你正在使用jQuery ...所以,用它来做这件事更容易。

  3. 您的病情并不需要。

试试这个:

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

DEMO

1

你不能将一些东西附加到输入,这是一个没有内容的自封闭元素,你应该使用按键事件

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

FIDDLE