轉文請標明 --- 出處:穆乙 http://www.cnblogs.com/pigtail/
execScript將指定的字符串當做腳本來執行,ie和早期的chrome支持,新版本的chrome已經不支持這個方法,下面我們模擬一個:
<!DOCTYPE HTML> <html> <head> <meta charset="gb2312"> <title>execscript將指定字符串作為腳本執行</title> </head> <body> <script> // 將指定字符串作為腳本執行 if (!window.execScript){ window.execScript = function(text){ if (!text){ return; } // 構建script元素 var script = document.createElement("SCRIPT"); script.setAttribute("type","text/javascript"); script.text = text; var head = document.head||document.getElementsByTagName("head")[0] // 開始執行 head.appendChild(script); // 執行完清除 head.removeChild(script); } } // 測試 execScript("alert(123)"); </script> </body> </html>
下面是jquery的方式
// Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } },
其實,我們知道另一個類似的方法,eval,也即window.eval。這兩個方法看起來一樣,其實本來就一樣!
alert(eval===window.eval);//true所有瀏覽器都一樣
但是也有不一樣的地方,可以測試一下面的函數:
var win ="全局"; function test(){ //window.eval("var win='局部'"); // 除ie外都是聲明一個全局變量會覆蓋掉原來全局變,ie聲明一個局部變量 execScript("var win='局部'");//只有ie支持,上面我們已經模擬了一個,同樣是聲明了一個全局變量,會覆蓋掉原來全局變量 //eval("var win='局部'");// 都是聲明一個局部變量 } test() alert(win);
所以我們還可以有另外一種模擬execScript的方法:
// 將指定字符串作為腳本執行 if (!window.execScript){ window.execScript = function execscript(text){ window.eval(text) } }
當然,可能還會想到另一個方法:Function構造函數
// 將指定字符串作為腳本執行 if (!window.execScript){ window.execScript = function execscript(text){ if (!typeof text ==="string") return; //window.eval(text) new Function("",text)() } }
同樣測試一下,結果除ie外均聲明一個局部變量,不會覆蓋已有全局變量。其實Function構造本來就是構造一個局部變量,包括ie
<!DOCTYPE HTML> <html> <head> <meta charset="gb2312"> <title>無標題文檔</title> </head> <body> <script> // 將指定字符串作為腳本執行 if (!window.execScript){ window.execScript = function execscript(text){ if (!typeof text ==="string") return; //window.eval(text) new Function(text)() } } var win ="全局"; function test(){ execScript("var win='局部'"); } test() alert(win);// 全局,ie局部
</script> </body> </html>