JavaScript使用DOM方法和属性

时间:2013-10-27 20:43:13

标签: javascript html dom methods

嘿伙计们我在这里有一些代码,它们应该在页面上创建HTML元素,今天将显示ID ='今天'如何使用textnode写出ID?谢谢你的帮助!这是我的完整代码:

HTML:

  <body>
  <h1>ToDo List - Date: <span id='today'>&nbsp;</span></h1>

  <div id="todolist">
<p>
    <input type="button" id="additem" value="Add Item">
</p>
  </div>

  <hr>

  <div>
<p>
    <input type="button" id="sortitems" value="Sort and Display Items">
</p>

<p id="displayitems">
</p>
   </div>
  </body>

使用Javascript:

 var $ = function (id){
return document.getElementById(id);
   }

  var TodaysDate = function () {
  var myDate = new Date();

  var myMonth = myDate.getMonth() + 1;
  var myDay = myDate.getDate();
  var myYear = myDate.getFullYear();

  var myResponse = myMonth + "/" + myDay + "/" + myYear;

  var myPara = document.createElement("p");
  var myP = document.getElementById('today');
  myP.appendChild(myPara);

  var myText = document.createTextNode(myResponse);
  myPara.appendChild(myText);

  }
  window.onload = function ()
  {
   $("today").onload = TodaysDate;
   $("sortitems").onclick = sortItem;
   $("additems").onclick = addItem;     
  }

2 个答案:

答案 0 :(得分:2)

跨度上载?跨度不会触发Onload。其他对象确实有一个load事件,例如:windows / frames,body,link,script和images

更改

 $("today").onload = TodaysDate;

 TodaysDate();

var myPara = document.createElement("p");
var myP = document.getElementById('today');
myP.appendChild(myPara);
var myText = document.createTextNode(myResponse);
myPara.appendChild(myText);

var myPara = document.createElement("p");
var myText = document.createTextNode(myResponse);
myPara.appendChild(myText);

var myP = $('today');
myP.appendChild(myPara);

答案 1 :(得分:1)

尝试替换此行:

$("today").onload = TodaysDate;

这一行:

TodaysDate();

因为SPAN标记不支持onload事件(请参阅 this answer)

尝试 here