Html 如何使用javascript在DIV框内写入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18808626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:26:23  来源:igfitidea点击:

How to write inside a DIV box with javascript

javascripthtmlcss

提问by Shawn

I'm making a mini-game where a player attacks a npc and in the center is a white box (div) that I call (log), because when the player damages/attacks the npc, I want to be able for that open white space to log what happened.

我正在制作一个小游戏,玩家攻击一个 npc,中间是一个白框(div),我称之为(日志),因为当玩家损坏/攻击 npc 时,我希望能够打开空白处记录发生的事情。

I'm using the getElementById(log) and then adding something along the lines of "document.write("You attacked X npc"), but its not working.

我正在使用 getElementById(log),然后添加一些类似于“document.write(”You Attacked X npc”) 的内容,但它不起作用。

Any idea on how I can get text INSIDE the box and not outside it? Thanks

关于如何在框内而不是在框外获取文本的任何想法?谢谢

回答by plalx

document.getElementById('log').innerHTML += '<br>Some new content!';
<div id="log">initial content</div>

回答by Muhammad Umer

You can use one of the following methods:

您可以使用以下方法之一:

document.getElementById('log').innerHTML = "text";

document.getElementById('log').innerText = "text";

document.getElementById('log').textContent = "text";

For Jquery:

对于 Jquery:

$("#log").text("text");

$("#log").html("text");

回答by Anshu Dwibhashi

HTML:

HTML:

<div id="log"></div>

JS:

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

回答by Anshu Dwibhashi

I would suggest Jquery:

我建议Jquery:

$("#log").html("Type what you want to be shown to the user");   

回答by joe_young

If you are using jQueryand you want to add content to the existing contents of the div, you can use .html()within the brackets:

如果您正在使用jQuery并且您想向 div 的现有内容添加内容,则可以.html()在括号内使用:

$("#log").html($('#log').html() + " <br>New content!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log">Initial Content</div>