转文请标明 --- 出处:穆乙 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>
