我们知道在.net后台弹出alert提示框有很多种方法,包括:
1.Page.Response.Write("<script>alert('提示内容!');</script>"); 白屏
2.HttpContext.Current.Response.Write("<script>alert('提示内容!');</script>"); 白屏
3.Page.ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('提示内容!');</script>"); 不白屏
4.Page.ClientScript.RegisterClientScriptBlock(GetType(), "message", "<script>alert('提示内容!');</script>"); 白屏
等等方法,但是我们知道他们的区别的具体的实现原理吗?
1.先来看前两个,前两个弹出框的共同特点就是会出现白屏,长得又有点像。肯定有什么共同点。
我们知道HttpResponse实际上是HttpContext的属性,在实例化HttpContext的时候可以传HttpResponse和HttpRequest两个参数。如果不知道,请参考http://msdn.microsoft.com/library/office/c2zzwa6y(v=vs.90)?cs-save-lang=1&cs-lang=cpp,对上面提到的三个类不熟的童鞋也请自行Google,这里不做介绍。
我想说的是HttpContext.Current实际上的HttpResponse参数就是this.Page.Response。这样就简单明了了,那么this.Page.Response.Write和HttpContext.Current.Response其实就是一个东西啦,都是Response.Write。虽然是一个东西,他们究竟做了什么使弹出框的时候白屏了呢。
我们使用浏览器的开发者工具比较alert前后html源码的区别。
alert前:
-
<!DOCTYPE html>
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head><title>
-
</title></head>
-
<body>
-
<form method="post" action="WebForm1.aspx" id="form1">
-
<div>
-
<input type="submit" name="Button1" value="Button" id="Button1" />
-
</div>
-
</form>
-
</body>
-
</html>
alert后:
-
<script>alert('提示内容!');</script>
-
<!DOCTYPE html>
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head><title>
-
</title></head>
-
<body>
-
<form method="post" action="WebForm1.aspx" id="form1">
-
<div>
-
<input type="submit" name="Button1" value="Button" id="Button1" />
-
</div>
-
</form>
-
</body>
-
</html>
不用看的很仔细,只要看最上面一行就可以了。这两种方法alert时在前台最上端增加了
<script>alert('提示内容!');</script>
这一行代码。我们可以看到,按照代码执行顺序,很明显在页面什么内容都没有显示的时候就会先执行alert,所以会导致白屏。
2.方法3和方法4是不是也很像,但是他们为什么效果不一样呢,让我们也来用上面的方法看一下alert后html源码的区别。
方法3 alert后:
-
<!DOCTYPE html>
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head><title>
-
</title></head>
-
<body>
-
<form method="post" action="WebForm1.aspx" id="form1">
-
<div>
-
<input type="submit" name="Button1" value="Button" id="Button1" />
-
</div>
-
<script>alert('提示信息!');</script>
-
</form>
-
</body>
-
</html>
在这个方法中alert脚本出现在form结束标签之前,所以当前面的内容都执行结束后才执行alert,因此不会显示白屏。
方法4 alert后:
-
<!DOCTYPE html>
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head><title>
-
</title></head>
-
<body>
-
<form method="post" action="WebForm1.aspx" id="form1">
-
<script>alert('提示内容!');</script>
-
<div>
-
<input type="submit" name="Button1" value="Button" id="Button1" />
-
</div>
-
</form>
-
</body>
-
</html>
我们发现alert脚本增加的位置是紧跟在form标签后的,也就是说会先于form标签中其他内容执行,因此出现白屏效果。
总结一下,使用注册脚本的方法3和方法4,首要前提是前台需要有form标签,然后两种方法注册的事件位置不同。使用这两种方法还可以注册一些其他事件,不要使用方法4时一定要注意,因为注册位置紧挨form,千万不要引用之后声明的标签内容,否则会出错。
以后大家需要在后台弹出提示框时,就可以根据需要,选择适当的方法啦。
--------------------- 本文来自 xiaozhudan1110 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xiaozhudan1110/article/details/18601719?utm_source=copy