首页 > Web开发 > 详细

原生js--insertAdjacentHTML

时间:2014-02-11 14:37:37      阅读:414      评论:0      收藏:0      [点我收藏+]

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;
}() );

原生js--insertAdjacentHTML

原文:http://www.cnblogs.com/charling/p/3543825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!