Javascript:将文字附加到div?

时间:2013-10-05 11:12:29

标签: javascript html

我想使用javascript将时钟附加到div内部。这是我的代码:

<script type="text/javascript">
//<![CDATA[
function makeArray() {
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}

var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var timer = document.write(months[month]+ " " +day + ", " + year);
document.getElementById('time').appendChild(timer);
//]]></script>

<div id='time'></div>

但它不起作用。帮我修理它。谢谢你。

3 个答案:

答案 0 :(得分:5)

试试这个:

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth();
var yy = date.getFullYear();
var year = (yy < 100) ? yy + 1900 : yy;

var timer = document.createElement('div');
timer.innerHTML = months[month] + " " + day + ", " + year;
document.getElementById('time').appendChild(timer);

演示here

答案 1 :(得分:2)

innerHTML 可以将文字写入div,因为您没有在此附加任何元素。

document.getElementById('time').innerHTML = months[month]+ " " +day + ", " + year;

for refernece:http://jsfiddle.net/SpgMm/2/

如果你真的想使用appendChild,最好使用createElement,然后将它附加到div。

希望有所帮助

P.S。只有在处理原始javascipt时才使用它,否则Jquery html方法是最佳选择。

答案 2 :(得分:1)

试试这个,这会对你有帮助

var months = new Array('January','February','March','April','May',
'June','July','August','September','October','November','December');
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var timer = months[month]+ " " +day + ", " + year;
$('#time').html(timer);

或者在Javascript中你可以写成

document.getElementById('time').innerHTML=timer;

小提琴Here