DOM javascript

来源:互联网 发布:mysql忘记密码 编辑:程序博客网 时间:2024/06/04 08:40

element.nodeName返回总是一个大写字母的值,即使元素在HTML文档里面是小写字母。

习惯:

1.分离javascript和CSS

2.考虑对属性,文本的检查

if(!document.getElementById("image")) return false;//检查属性

if(!document.getElementsByTagName) return false;//检查对方法是否支持

3.考虑对javascript不支持的后果


把多个javascript函数绑定到onload事件时

window.onload = firstFunction;

window.onload = seondFunction;

实际只会执行第二个事件,可以通过:

window.onload = function(){

firstFunction();

secondFunction();

}

也可以通过以下函数操作——simon Willison。其功能:

(1)把现有的window.onload事件处理函数的值存入变量oldonoad

(2)如果在这个处理函数上还没有绑定任何函数,就像平时那样把新函数添加给它

(3)若果在这个处理函数上已经绑定了一些函数,就把新函数追加到现有指令的末尾

function addLoadEvent(func){

var oldonload = window.onload;

if(typeof window.onload != 'function'){

window.onload = func;

}else{

window.onload = function(){

oldonload();

func();

}

}

}

addLoadEvent(firstFucntion);

addLoadEvent(secondFunction);


document.createElement(nodename)方法创建一个元素点,并根据nodename自动创建nodeType

parent.appendChild(child)将child元素节点加入到parent的节点树后。

当然文本节点不属于元素节点,有自己的创建方式:document.createTextNode(text)并且需要把它添加到元素节点中。

targetElement.parentNode.insertBefore(newElement.targetElement)方法可以将节点插入到目标节点前

自己编写的insertAfter()——DOM本身没有这个方法

function insertAfter(newElement,targetElement){

var parent = targetElement.parentNode;

if(parent.lastChild == targetElement){

 parent.appendChild(newElement);

}else{

parent.insertBefore(newElement, targetElement.nextSibling);//下一个兄弟节点

}

}

例子:

function preparePlaceholder() {
  if (!document.createElement) return false;
  if (!document.createTextNode) return false;
  var placeholder = document.createElement("img");
  placeholder.setAttribute("id","placeholder");
  placeholder.setAttribute("src","images/placeholder.gif");
  placeholder.setAttribute("alt","my image gallery");
  var description = document.createElement("p");
  description.setAttribute("id","description");
  var desctext = document.createTextNode("Choose an image");
  description.appendChild(desctext);
  var gallery = document.getElementById("imagegallery");
  document.getElementsByTagName("body")[0].appendChild(placeholder);
  document.getElementsByTagName("body")[0].appendChild(description);
}


0 0