JavaScript DOM修改文档树方法实例(1)(3)
辅助函数
appendChild()和insertBefore()都有2个参数,但是我们在应用的时候,还要注意参数的先后顺序。既然这么麻烦我们还是自己写一些辅助函数来代替原有的appendChild()和insertBefore()。在另一个元素之前插入元素的函数:
- <script type="text/javascript">
- //insertBefore()的代替方法
- function before( parent, before, elem ) {
- // Check to see if no parent node was provided
- //检查parent是否传入
- if ( elem == null ) {
- elem = before;
- before = parent;
- parent = before.parentNode;
- }
- // Get the new array of elements
- //获取元素的新数组
- var elems = checkElem( elem );
- // Move through the array backwards,
- // because we’re prepending elements
- //向后遍历数组
- //因为我们向前插入元素
- for ( var i = elems.length - 1; i >= 0; i-- ) {
- parent.insertBefore( elems[i], before );
- }
- }
- </script>
为另一个元素添加一个子元素:
- <script type="text/javascript">
- //appendChild()的代替方法
- function append( parent, elem ) {
- // Get the array of elements
- //获取元素数组
- var elems = checkElem( elem );
- // Append them all to the element
- //把它们所有都追加到元素中
- for ( var i = 0; i <= elems.length; i++ ) {
- parent.appendChild( elems[i] );
- }
- }
- </script>
before和append的辅助函数:
- <script type="text/javascript">
- function checkElem( elem ) {
- // If only a string was provided, convert it into a Text Node
- //如果只提供字符串,那就把它转换为文本节点
- return elem && elem.constructor == String ?
- document.createTextNode( elem ) : elem;
- }
- </script>
注意:constructor的用法。
有时你可能需要对变量进行类型检查,或者判断变量是否已定义。有两种方法可以使用:typeof函数与constructor属性。typeof可以检查到变量是否有定义,而construct只能检查已定义变量的类型。
移除所有的子节点的辅助函数:
- <script type="text/javascript">
- function empty( elem ) {
- while (elem.firstChild){
- remove(elem.firstChild);
- }
- /*
- //我们可以使用firstChild来代替childNodes[0]
- while (elem.childNodes[0])
- remove(elem.childNodes[0]);
- * /
- }
- function remove( elem ) {
- if ( elem ) elem.parentNode.removeChild( elem );
- }
- </script>