原生js--insertAdjacentHTML

insertAdjacentHTML是IE浏览器提供向DOM中插入html字符串的方法,字符串会自动生成在DOM树中。

其调用方式为elem.insertAdjacentHTML( position, htmlStr )

elem 向哪个DOM的标签出插入字符串

position 有四个选项 "beforeBegin" "afterEnd" "afterBegin" "beforeEnd"分别指在elem的开始标签之前、结束标签之后、开始标签之后、结束标签之前插入htmlStr

htmlStr 字符串(不是DOM元素)

以下是在《javascript权威指南》中摘抄的,重新封装并重命名了该功能的Insert对象。并同时解决insertAdjacentHTML的浏览器兼容性问题

/**
 * 在开始或结束标签的前后插入html字符串
 * before 在开始标签之前插入html字符串
 * after 在结束标签之后插入html字符串
 * atStart 在开始标签之后插入字符串
 * atEnd 在结束标签之前插入字符串
 */
Insert = ( function(){
    if( document.createElement( "div" ).insertAdjacentHTML ){
        return {
            // e element, h html
            before : function( e, h ){
                // beforebegin大小写均可, h {string} html字符串或text均可
                e.insertAdjacentHTML( "beforebegin", h );
            },
            after : function( e, h ){
                e.insertAdjacentHTML( "afterend", h );
            },
            atStart : function( e, h ){
                e.insertAdjacentHTML( "afterbegin", h );
            },
            atEnd : function( e, h ){
                e.insertAdjacentHTML( "beforeEnd", h );
            }
        };
    }

    function fragment( html ){
        var tmpDiv = document.createElement( "div" ),
            frag = document.createDocumentFragment();
        tmpDiv.innerHTML = html;
        while( tmpDiv.firstChild ){
            frag.appendChild( tmpDiv.firstChild );
        }
        return frag;
    }

    var Insert = {
        before : function( e, h ){
            e.parentNode.insertBefore( fragment( h ), e );
        },
        after : function( e, h ){
            // 当e.nextSibling为空时,insertBefore方法会将frament(h)插入到最后
            e.parentNode.insertBefore( fragment( h ), e.nextSibling );
        },
        atStart : function( e, h ){
            e.insertBefore( fragment( h ), e.firstChild );
        },
        atEnd : function(){
            e.appendChild( fragment( h ) );
        }
    };

    // 同时解决insertAdjacentHTML的兼容性问题
    Element.prototype.insertAdjacentHTML = function( pos, html ){
        switch( pos.toLowerCase() ){
            case "beforebegin" : return Insert.before( this, html );
            case "afterend" : return Insert.after( this, html );
            case "afterbegin" : return Insert.atStart( this, html );
            case "beforeend" : return Insert.atEnd( this, html );
        }
    };

    return Insert;
}() );

 

posted @ 2014-02-11 09:29  charling  阅读(6955)  评论(0编辑  收藏  举报