使用JavaScript在"div"上写文本

Raú*_*vas 17 html javascript

每当我想在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>
Run Code Online (Sandbox Code Playgroud)

它做了它必须正确做的事情,但然后它只切换回文本框,我刚写的评论消失了.知道这里发生了什么吗?

非常感谢您的参与.

Joe*_*Joe 18

这是因为您提交的是表格.

快速解决:

<input type="submit" value="Ready!" onClick="writeComment()" />
Run Code Online (Sandbox Code Playgroud)

<input type="button" value="Ready!" onClick="writeComment()" />
Run Code Online (Sandbox Code Playgroud)

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

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

    document.getElementById('comments').innerHTML = comment;
    e.preventDefault();
    return false;
}
Run Code Online (Sandbox Code Playgroud)


n8w*_*wrl 5

发生了什么事情是你的表单提交,页面刷新,div回到它预先设置的JavaScript内容.

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