日期:2014-05-16  浏览次数:20385 次

如何用javascript删除或禁用同页面的另一个javascript
已知在一个html中有若干javascript,现要求用某个javascript删除最后一个javascript,实例如下
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<script type="text/javascript">
document.write("js1\n");
</script>
<script type="text/javascript">
document.write("js2\n");
</script>
<script type="text/javascript">
document.write("js3\n");
</script>
<script type="text/javascript">
document.write("js4\n");
</script>
<script type="text/javascript">
/*删除最后一个javascript,使之不执行,页面上不会出现 js5 */
</script>
<script type="text/javascript" id="target">
document.write("js5\n");
</script>
</body>
</html>



------解决方案--------------------
js可以实现,这么做就可以了
JScript code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<script type="text/javascript">
document.write("js1\n");
</script>
<script type="text/javascript">
document.write("js2\n");
</script>
<script type="text/javascript">
document.write("js3\n");
</script>
<script type="text/javascript">
document.write("js4\n");
</script>
<script type="text/javascript">
//实现的原理是重写目标代码段里调用的第一个函数,从里面throw一个异常出来,终结掉整个代码段的执行
//首先保存write函数,以便执行完以后恢复。如果你不需要恢复,那么就不需要保存
var temp=document.write;
document.write=function(){throw 1;};
</script>
<script type="text/javascript" id="target">
document.write("js5\n");
alert(1);
</script>
<script type="text/javascript">
//恢复write函数,以便其他调用
document.write=temp;
</script>
<script type="text/javascript">
document.write("js6\n");
</script>
</body>
</html>