栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js中AppendChild与insertBefore的用法详细解析

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js中AppendChild与insertBefore的用法详细解析

appendChild定义
appendChild(newChild: Node) : Node
Appends a node to the childNodes array for the node.
Supported: IE 5.0+, Mozilla 1.0+, Netscape 6.0+, Safari 1.0+, Opera 7.0+
添加一个节点到指定的节点的子节点数组中,读起来好象有点拗口,简单地说就是将元素添加到指定的节点中

appendChild用法
target.appendChild(newChild)

newChild作为target的子节点插入最后的一子节点之后

appendChild例子
var newElement = document.document.createElement('label');
newElement.Element.setAttribute('value', 'Username:');

var usernameText = document.document.getElementById('username');
usernameText.appendChild(newElement);

insertBefore定义
The insertBefore() method inserts a new child node before an existing child node.

insertBefore() 方法的作用是:在现有的子节点前插入一个新的子节点

insertBefore用法
target.insertBefore(newChild,existingChild)

newChild作为target的子节点插入到existingChild节点之前

existingChild为可选项参数,当为null时其效果与appendChild一样

insertBefore例子
var oTest = document.getElementById("test");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";

oTest.insertBefore(newNode,oTest.childNodes[0]); 

 
好了那么有insertBefore的应该也有insertAfter吧?
好那我们来用Aptana编写一个例子吧,但Aptana的智能提示告诉我其实没有insertAfter这个方法
那么就自己定义一个罗:)

insertAfter定义
function insertAfter(newEl, targetEl)
{
      var parentEl = targetEl.parentNode;

      if(parentEl.lastChild == targetEl)
      {
           parentEl.appendChild(newEl);
      }else
      {
           parentEl.insertBefore(newEl,targetEl.nextSibling);
      }           
}

 
insertAfter用法与例子
var txtName = document.getElementById("txtName");
var htmlSpan = document.createElement("span");
htmlSpan.innerHTML = "This is a test";
insertAfter(htmlSpan,txtName);

将htmlSpan 作为txtName 的兄弟节点插入到txtName 节点之后

总结:
1、appendChild和insertBefore是做对节点的方法来使用的,而insertAfter只是自定义的一个函数

2、insertBefore相对于appendChild来说,比较灵活可以将新的节点插入到目标节点子节点数组中的任一位置。

3、使用appendChild和insertBefore来插入新的节点前提是,其兄弟节点必须有共同的父节点

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/108968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号