我正在尝试将document.write
更改为id
或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上检查输出或编辑代码
答案 0 :(得分:2)
它可能对您有帮助
document.getElementById("demo").innerHTML = weekday[d.getDay()] + " "+daynumber[d.getDate()] + " "+monthname[d.getMonth()] + " "+d.getFullYear();
答案 1 :(得分: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>
答案 2 :(得分: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>