深入理解javascript动态插入技术(5)

insert方法执行jQuery的domManip方法相应的机能(dojo则为place方法),但insert方法每次处理一个元素节点,不像jQuery那样处理一组元素节点。群集处理已经由上面batch方法分离出去了。

复制代码 代码如下:


insert : function(el,stuff,where){
     //定义两个全局的东西,提供内部方法调用
     var doc = el.ownerDocument || dom.doc,
     fragment = doc.createDocumentFragment();
     if(stuff.version){//如果是dom对象,则把它里面的元素节点移到文档碎片中
         stuff.forEach(function(el){
             fragment.appendChild(el);
         })
         stuff = fragment;
     }
     //供火狐与IE部分元素调用
     dom._insertAdjacentElement = function(el,node,where){
         switch (where){
             case 'beforeBegin':
                 el.parentNode.insertBefore(node,el)
                 break;
             case 'afterBegin':
                 el.insertBefore(node,el.firstChild);
                 break;
             case 'beforeEnd':
                 el.appendChild(node);
                 break;
             case 'afterEnd':
                 if (el.nextSibling) el.parentNode.insertBefore(node,el.nextSibling);
                 else el.parentNode.appendChild(node);
                 break;
         }
     };
      //供火狐调用
     dom._insertAdjacentHTML = function(el,htmlStr,where){
         var range = doc.createRange();
         switch (where) {
             case "beforeBegin"://before
                 range.setStartBefore(el);
                 break;
             case "afterBegin"://after
                 range.selectNodeContents(el);
                 range.collapse(true);
                 break;
             case "beforeEnd"://append
                 range.selectNodeContents(el);
                 range.collapse(false);
                 break;
             case "afterEnd"://prepend
                 range.setStartAfter(el);
                 break;
         }
         var parsedHTML = range.createContextualFragment(htmlStr);
         dom._insertAdjacentElement(el,parsedHTML,where);
     };
     //以下元素的innerHTML在IE中是只读的,调用insertAdjacentElement进行插入就会出错
     // col, colgroup, frameset, html, head, style, title,table, tbody, tfoot, thead, 与tr;
     dom._insertAdjacentIEFix = function(el,htmlStr,where){
         var parsedHTML = dom.parseHTML(htmlStr,fragment);
         dom._insertAdjacentElement(el,parsedHTML,where)
     };
     //如果是节点则复制一份
     stuff = stuff.nodeType ?  stuff.cloneNode(true) : stuff;
     if (el.insertAdjacentHTML) {//ie,chrome,opera,safari都已实现insertAdjactentXXX家族
         try{//适合用于opera,safari,chrome与IE
             el['insertAdjacent'+ (stuff.nodeType ? 'Element':'HTML')](where,stuff);
         }catch(e){
             //IE的某些元素调用insertAdjacentXXX可能出错,因此使用此补丁
             dom._insertAdjacentIEFix(el,stuff,where);
         }     
     }else{
         //火狐专用
         dom['_insertAdjacent'+ (stuff.nodeType ? 'Element':'HTML')](el,stuff,where);
     }
 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdzyyg.html