coos.$script 动态插入脚本并执行的方法
/**? ?* 动态插入脚本并执行? ?* @param scriptStr? ?* @param el dom元素对象或ID 可以不传入? ?* @exsample coos.$script("<script>alert(2);<\/script>");? ?*/? coos.$script = function(scriptStr,el)? {? ? ? ? ? var el = coos.$obj(el);? ? ? ? ? if(!el){? ? ? ? ? ? ? ? ? var div = coos.$create("div");? ? ? ? ? ? ? ? ? div.style.display = "none";? ? ? ? ? ? ? ? ? coos.$append(document.body,div);? ? ? ? ? ? ? ? ? el = div;? ? ? ? ? }? ? ? ? ? if(coos.browser.msie){? ? ? ? ? ? ? ? ? scriptStr = '<div style="display:none">ie</div>' + scriptStr;? ? ? ? ? ? ? ? ? //当节点被移除的时候,ie会重新解析节点内部的html,有脚本则会执行相关的脚本,script要加上defer属性? ? ? ? ? ? ? ? ? scriptStr = scriptStr.replace(/<script([^>]*)>/gi,'<script$1 defer>');? ? ? ? ? ? ? ? ? el.innerHTML = scriptStr;? ? ? ? ? ? ? ? ? el.removeChild(el.firstChild);? ? ? ? ? }else{? ? ? ? ? ? ? ? ? var el_next = el.nextSibling;? ? ? ? ? ? ? ? ? var el_parent = el.parentNode;? ? ? ? ? ? ? ? ? el_parent.removeChild(el);? ? ? ? ? ? ? ? ? el.innerHTML = scriptStr;? ? ? ? ? ? ? ? ? if (el_next) {? ? ? ? ? ? ? ? ? ? ? ? ? el_parent.insertBefore(el, el_next);? ? ? ? ? ? ? ? ? }else {? ? ? ? ? ? ? ? ? ? ? ? ? el_parent.appendChild(el);? ? ? ? ? ? ? ? ? }? ? ? ? ? }?
};?
?
源码请看coos脚本库
?
http://code.google.com/p/coos/source/browse/trunk/coos/WebRoot/scripts/labs/base/coos.ext.%24.js
?
测试页面
<html>? <head>? <title>test_$</title>? <meta http-equiv="Content-type" content="text/html; charset=utf-8">? <script type="text/javascript" src="../scripts/coos.js"></script>? </head>? <body>? <div>test_$ page</div>? <script type="text/javascript">? coos.$script("<script>alert(2);<\/script>");? </script>? </body>? </html>??