在“div”上撰写文字使用JavaScript [英] Writing text on "div" using JavaScript

查看:143
本文介绍了在“div”上撰写文字使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < p>< p>< p>< ; HTML> 

< body>
< div id =comments>

< / div>
< form name =forma>
< textarea name =commentUserid =commentUsercols =40rows =5>
此处评论...
< / textarea>< br>
< input type =submitvalue =Ready! onClick =writeComment()/>
< / form>

< script type =text / javascript>

函数writeComment()
{
var comment = document.forma.commentUser.value;
alert(评论);

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


}


< / script>
< / body>

< / html>

它可以正确地做到这一点,但它只会切换回文本框,评论我只写了消失。任何关于这里发生了什么的想法?



非常感谢您的宝贵时间。

解决方案

快速修正:

 < input type =submitvalue =Ready! onClick =writeComment()/> 

 < input type =buttonvalue =Ready! onClick =writeComment()/> 

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

 函数writeComment(e){
var comment = document.forma.commentUser.value;
alert(评论);

document.getElementById('comments')。innerHTML = comment;
e.preventDefault();
返回false;
}


I'm having some trouble whenever I want to add some text to my div tag, here's my code:

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

It does what it has to do correctly, but then it switches back to the text box only and the comment I just wrote disappears. Any idea of what's going on here?

Thank you so much for your time.

解决方案

It is because you are submitting the form.

Quick fix:

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

to

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

In addition, you are able to prevent the default action of an input. Basically telling the browser the you are going to handle the action with preventDefault:

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

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

这篇关于在“div”上撰写文字使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆