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

时间:2013-12-06 21:39:21

标签: javascript button

<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>

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

2 个答案:

答案 0 :(得分:2)

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

在文档自动加载调用document.write()后使用document.open(),“如果目标中存在文档,则此方法将其清除(请参阅示例)。”

要为您的用例解决此问题,您只需在页面中附加textNode或元素即可。

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

假设这个标记你可以做到append这样的事情到页面的末尾。

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

作为旁注:你应该有一个容器(可能是div元素),其ID值可以附加到身体而不是身体。如果您希望将来使用节点,它将为您提供更多控制。我还建议你不要使用内联事件监听器。

答案 1 :(得分:-1)

你必须有一个“目标”。如果你没有 - 动态创建它,例如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/