而不是document.write,输出id的div / class

问题描述 投票:2回答:3

我正在尝试将document.write更改为输出idor class所以我可以将它添加到div我尝试使用document.getElementById("demo").innerHTML但它似乎不起作用,不确定我是否正确地做到了。

<html>
<body>
<p id="demo"></p>
<script type="text/javascript">
var d=new Date()
var daynumber=new Array("0","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st","32nd")
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("January","Febuary","March","April","May","June","July","August","September","October","November","December")
document.write(weekday[d.getDay()] + " ")
document.write(daynumber[d.getDate()] + " ")
   // document.write(d.getDate() + " ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>

</body>
</html>

检查jsfiddle上的输出或编辑代码

javascript html html5
3个回答
2
投票

它可能对你有帮助

document.getElementById("demo").innerHTML = weekday[d.getDay()] + " "+daynumber[d.getDate()] + " "+monthname[d.getMonth()] + " "+d.getFullYear();

0
投票

您可以在目标元素上分配一个带闭包的新函数。

但是,正如Chris Barr指出的那样,“覆盖内置的JavaScript函数是一个坏主意。”

document.write = (element => string => element.innerHTML += string)(document.getElementById('out'));

document.write('foo<br>');
document.write('bar');
<div id="out"></div>

0
投票

你可以使用document.getElementById('idname')甚至document.querySelector('#idname')

这是一个包含代码的小型演示

//Vars
var d = new Date();
var outputElement = document.getElementById("current-date");

//Date Text arrays
var daynumber = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st", "32nd"];
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthname = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

//Build up a string
var dateStr = weekday[d.getDay()] +
  ", the " + daynumber[d.getDate() - 1] +
  " of " + monthname[d.getMonth()] +
  ", " + d.getFullYear();

//Output to screen
outputElement.innerHTML = dateStr
#current-date {
  padding: 1px 4px;
  background: #EFEFEF;
  border: 1px solid #CCC;
  border-radius: 4px;
}
<p>
  Today's date is <strong id="current-date"></strong>
</p>
© www.soinside.com 2019 - 2024. All rights reserved.