用JavaScript在div内写文本? [英] Write text inside a div from JavaScript?
问题描述
我有一个JavaScript函数,该函数使用document.write()
写入页面.我的问题是,当我单击该按钮以调用该函数时,document.write()
会将我已有的内容替换为正在编写的内容.有没有一种方法可以将文本从JavaScript写入特定的div?
I have a JavaScript function that uses document.write()
to write to the page. My issue is that when I click the button to call the function, document.write()
replaces what I already had with what I am writing. Is there a way to write text to a specific div from JavaScript?
这是我的HTML代码:
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="javascript.js">
</script>
<script>
// Calling the Google Maps API
</script>
<script>
<!-- JavaScript to load Google Maps -->
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>this -->
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
</div>
</div>
</body>
...以及我的JavaScript代码(我从互联网上得到的只是用于测试的东西):
function todaydate() {
var today_date = new Date();
var myyear = today_date.getYear();
var mymonth = today_date.getMonth() + 1;
var mytoday = today_date.getDate();
document.write("<h1>" + myyear + "/" + mymonth + "/"+mytoday + "/h1">);
}
我希望文本位于按钮的正下方.任何帮助,将不胜感激.
I would like the text to be right below the button. Any help would be appreciated.
谢谢, 乔什
推荐答案
您应避免使用document.write
.您最好将结果放到另一个div:
You should avoid document.write
. You'd better put your results to another div:
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
<div id="results"></div> <!-- Added div ! -->
</div>
然后
function todaydate() {
var today_date=new Date();
var myyear=today_date.getYear();
var mymonth=today_date.getMonth() + 1;
var mytoday=today_date.getDate();
document.getElementById('results').innerHTML ="<h1>" + myyear + "/" + mymonth + "/" + mytoday + "</h1>";
}
如您所见,我们正在使用.innerHTML
将结果写入results
div.
As you can see, we're writing the results to the results
div with .innerHTML
.
希望这会有所帮助.干杯
Hope this helps. Cheers
这篇关于用JavaScript在div内写文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!