html追加dom(div,style,javascript等)闭包
2016/03/12    标签: javascript   

在body尾部和头部追加dom,body尾部追加script,head内追加样式的javascript代码

 var creatArticle=function(obj) {
                      /***
                                obj={
                                style:"",//type:string
                                html:"",  //type:string
                                script:"" //type:string
                                local:''//type:string,start页面头部,end页面尾部插入.
                                }
                            ***/
                        (function(doc){
                        try {
                            if (obj.style) {
                                var styleEleWp = doc.createElement('div');
                                styleEleWp.innerHTML = "_<style type='text/css'>" + obj.style + "</style>";
                                doc.getElementsByTagName('head')[0].appendChild(styleEleWp.children[0]);
                            }
                            if (obj.html) {
                                var htmlEle = doc.createElement('div');
                                htmlEle.innerHTML = obj.html;
                                var htmlEleTrue = htmlEle.children;

                                if (typeof (obj.local) == "undefined" || (obj.local !== "start")) {
                                    for (var x in htmlEleTrue) {
                                        if (!isNaN(x)) {
                                            doc.getElementsByTagName("body")[0].appendChild(htmlEleTrue[x].cloneNode(true));
                                        };
                                    }
                                } else {
                                    for (var j in htmlEleTrue) {
                                        if (!isNaN(j)) {
                                            doc.getElementsByTagName("body")[0].insertBefore(htmlEleTrue[j].cloneNode(true), doc.getElementsByTagName("body")[0].children[0]);
                                        };
                                    }
                                }
                            }
                            if (obj.script) {
                                var scriptEl = document.createElement("script");
                                scriptEl.type = "text/javascript";
                                scriptEl.text = obj.script;
                                doc.getElementsByTagName("body")[0].appendChild(scriptEl);
                            }
                        } catch(e) {
                        }

                        })(document)
                      }

示例DEMO:

1.在body前插入dom,body尾追加script,head尾追加样式



2.在body尾插入dom,body尾追加script,head尾追加样式