将文本框中的文本打印到屏幕上

Have the text from a text box print to the screen

本文关键字:文本 屏幕 打印      更新时间:2024-04-05
<html>
<script>
var x= document.getElementById('myText').innerHTML;
function go(){
document.write(x);
}
</script>
<body>
<input type="text" id="myText" size="1" value="" />
<input type="button" id="button" value="button" onclick="go()"/>
</body>

我无法从文本框中获取文本以打印到屏幕上。我也不希望按钮在文本打印到屏幕上时

消失

对正在发生的事情给出一些解释:

文档加载后使用 document.write(( 会自动调用 document.open((,"如果目标中存在文档,此方法会清除它(参见示例(。

为了解决您的用例,您只需将 textNode 或元素附加到您希望它去的页面中。

<body>
<input type="text" id="myText" size="1" value="" />
<input type="button" id="button" value="button" onclick="go()"/>
</body>

假设此标记,您可以执行类似操作以将其附加到页面末尾。

var myText = document.getElementById('myText');
function go() {
  document.body.appendChild(document.createTextNode(myText.value));
}

作为旁注:您应该有一个带有 ID 值的容器(可能是div 元素(,您可以将这些值附加到其中而不是正文中。如果您想将来使用节点,它将为您提供更多控制权。我还敦促您不要使用内联事件侦听器。

你必须

有一个"目标"。如果您没有 - 请即时创建它,例如 SPAN:

function go(){
    var sp =  document.createElement('span')
    sp.innerHTML = document.getElementById('myText').value;
    document.documentElement.appendChild(sp);
}

顺便说一句,文本输入元素没有.innerHTML它们有.value

演示:http://jsfiddle.net/PKFG8/

更新

这个略微更新的功能会在新行上打印每个新输入,这也是为了增加便利性,可以清除用户输入并在每次单击后重新关注它:

function go(){
    var txt = document.getElementById('myText');
    var sp =  document.createElement('div')
    sp.innerHTML = txt.value;
    document.documentElement.appendChild(sp);
    txt.value = '';
    txt.focus();
}

演示 2:http://jsfiddle.net/PKFG8/2/