将Javascript document.write更新为DOM document.getElementById

时间:2018-04-08 17:09:33

标签: javascript dom document.write

我有以下运费估算提供商,但我不知道如何使用更实用的解决方案更新代码以替换document.write,例如document.getElementById innerHTML

var myDate = new Date();
if (myDate.getHours() < 14) // less than 2pm
{
  var daystodeliver = [3, 2, 2, 2, 4, 5, 3][myDate.getDay()];
} else {
  var daystodeliver = [3, 3, 3, 5, 4, 5, 3][myDate.getDay()];
}
myDate.setDate(myDate.getDate() + daystodeliver);

document.write(['Sunday', 'Monday', 'Tuesday', 'Wed', 'Thurs', 'Friday', 'Saturday'][myDate.getDay()]);
var dayofmonth = myDate.getDate();

suffix = ((dayofmonth < 10) || (dayofmonth > 20)) ? ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'][dayofmonth % 10] : 'th';

document.write(' ' + dayofmonth + suffix + ' ');

document.write(['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug','Sept', 'Oct', 'Nov', 'Dec'][myDate.getMonth()]);

2 个答案:

答案 0 :(得分:0)

尝试以下内容

var daystodeliver;
var myDate=new Date();
var weeks = ['Sunday','Monday','Tuesday','Wed','Thurs','Friday','Saturday'];
var months = ['Jan','Feb','March','April','May','June','July','Aug',
              'Sept','Oct','Nov','Dec'];

var day = myDate.getDay();
if ( myDate.getHours() < 14 ) {
  daystodeliver = [3,2,2,2,4,5,3][day];
} else {
  daystodeliver = [3,3,3,5,4,5,3][day];
}

myDate.setDate(myDate.getDate() + daystodeliver);
var newday = myDate.getDay();
var dayofmonth =  myDate.getDate();
var newMonth = myDate.getMonth();

var toPrint = weeks[newday];
var suffix = ((dayofmonth < 10)||(dayofmonth > 20)) ?   
['th','st','nd','rd','th','th','th','th','th','th'][dayofmonth % 10] : 'th';

toPrint += ' ' + dayofmonth + suffix + ' ';
toPrint += months[newMonth];

// this is the line that does the job of adding text to DOM
// ---------------------------------------------------------
document.getElementById('my_element_id').innerHTML = toPrint;
// ---------------------------------------------------------

答案 1 :(得分:0)

您需要创建一个像div这样的html标记,然后用您的内容更新其内部HTML值。

var myDate = new Date();
if (myDate.getHours() < 14) // less than 2pm
{
  var daystodeliver = [3, 2, 2, 2, 4, 5, 3][myDate.getDay()];
} else {
  var daystodeliver = [3, 3, 3, 5, 4, 5, 3][myDate.getDay()];
}
myDate.setDate(myDate.getDate() + daystodeliver);

document.getElementById("divDate").innerHTML += ['Sunday', 'Monday', 'Tuesday', 'Wed', 'Thurs', 'Friday', 'Saturday'][myDate.getDay()];

var dayofmonth = myDate.getDate();

suffix = ((dayofmonth < 10) || (dayofmonth > 20)) ? ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'][dayofmonth % 10] : 'th';

document.getElementById("divDate").innerHTML += ' ' + dayofmonth +suffix + ' ';

document.getElementById("divDate").innerHTML += ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug','Sept', 'Oct', 'Nov', 'Dec'][myDate.getMonth()];
<div id="divDate"></div>