2014-03-31 68 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