我在做一个关于评论的测试。我想要的就是有一个小的文本框,你可以在其中输入内容,还有一个按钮,上面写着"Add Comment“,它将document.write();你放在add comment下的文本框中的内容。但是我遇到了一个问题,document.write();似乎正在移除所有其他从javascript (即文本区域和“添加评论”按钮)写出来的超文本标记语言。当我按下“添加评论”按钮时,我在文本区域中写的内容填满了整个屏幕,似乎遮住了剩下的部分。下面是我的代码:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p>Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
document.writeln(input);
}
</script>
</body>
</html>发布于 2013-11-29 03:48:26
一旦文档加载完成,就不能使用document.write。如果这样做,浏览器将打开一个新文档,并将其替换为当前文档。因此,这是document.write的设计行为
最好使用innerHTML将超文本标记语言放入元素中
试着这样做:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>发布于 2013-11-29 03:54:47
好的,而不是使用文档编写,你应该追加或填充目标元素,我对你的代码做了一点修改,这可能会对你有帮助。
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>如果您只想从原始文档中添加内容,则可以将其用作
test.innerHTML = test.innerHTML + input; 此外,
发布于 2013-11-29 03:58:51
不使用document.write().Instead使用innerHTML
注意:您的代码将无法工作,因为您使用的是tf.value,其中tf是没有值属性的文本区域的对象。所以我推荐使用innerHTML。
<html>
<script language="JavaScript">
<head>
function add1(){
var tf = document.getElementById('tf');
add2(tf.innerHTML);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>https://stackoverflow.com/questions/20273805
复制相似问题