使用JavaScript在“div”上写文本

时间:2011-08-25 19:06:35

标签: javascript html

每当我想在div标签中添加一些文字时,我遇到了一些麻烦,这是我的代码:

<html>

<body>
<div id="comments">

</div>
<form name="forma">
<textarea name="commentUser" id="commentUser" cols="40" rows="5">
Comments here...
</textarea><br>
<input type="submit" value="Ready!" onClick="writeComment()" />
</form>

<script type="text/javascript" >

function writeComment()
    {
    var comment = document.forma.commentUser.value;
    alert(comment);

    document.getElementById('comments').innerHTML=comment;


    }


</script>
</body>

</html>

它完成了它必须正确执行的操作,但之后它又切换回文本框,我刚写的评论消失了。知道这里发生了什么吗?

非常感谢您的时间。

10 个答案:

答案 0 :(得分:17)

这是因为您正在提交表单。

快速修复:

<input type="submit" value="Ready!" onClick="writeComment()" />

<input type="button" value="Ready!" onClick="writeComment()" />

此外,您还可以阻止输入的默认操作。基本上告诉浏览器您将使用preventDefault来处理操作:

function writeComment(e) {
    var comment = document.forma.commentUser.value;
    alert(comment);

    document.getElementById('comments').innerHTML = comment;
    e.preventDefault();
    return false;
}

答案 1 :(得分:5)

正在发生的事情是您的表单正在提交,页面正在刷新,而div又会回到其预先设置的JavaScript内容。

尝试将按钮上的type ='submit'换成'按钮'。

答案 2 :(得分:1)

当您单击提交按钮时,表单将被提交,从而导致整个页面重新加载。您需要从提交按钮的onclick返回false以防止它:

<input type="submit" value="Ready!" onclick="writeComment(); return false;" />

或者,如果您不希望该按钮将表单更改type="submit"提交到type="button"

PS。使用onclick属性是不好的做法。而是使用纯JS将处理程序绑定到click事件。

答案 3 :(得分:1)

这是因为您不仅使用常规按钮而且使用提交按钮,默认情况下会将表单提交给服务器。您可以看到您的评论是通过URL提交的,因为您没有指定方法(GET和POST以及GET是默认值)。

简单地写一下:

onclick="writeComment();return false;"

返回FALSE会阻止默认行为 - 提交表单。

答案 4 :(得分:0)

它向服务器发出另一个请求,导致页面再次呈现。

只需从writeComment返回false。

答案 5 :(得分:0)

您必须阻止表单提交:

<input type="submit" value="Ready!" onClick="writeComment(); return false;" />

答案 6 :(得分:0)

更改此

<input type="submit" value="Ready!" onClick="writeComment()" /> 

到此:

<input type="submit" value="Ready!" onClick="writeComment(); return false;" /> 

答案 7 :(得分:0)

尝试<input type="button" value="Ready!" onClick="writeComment()" />

答案 8 :(得分:0)

你应该切换
<input type="submit" value="Ready!" onClick="writeComment()" />
<input type="button" value="Ready!" onClick="writeComment()" />

答案 9 :(得分:0)

或者其他选项是将您的submit转换为button并将其从表单中删除,现在按钮可以存在于表单之外,而且从您粘贴的代码中我不明白为什么你必须使用表单,这意味着当您单击“就绪”按钮时不会重新加载您的页面。