我需要在前端检测postback,以便在页面加载时使用JQuery更改类。我该怎么做?
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
从这篇文章中获取:
在服务器端使用以下代码:
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
...
if(isPostBack) {
// do your thing
}
我把这个变量放在了我的ASP.NET Web Forms页面的头部标签中。
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
变量包含布尔值。比较可能可以缩短。
简单:
如果你正在使用jQuery,它必须放在之后(否则jQuery会出问题):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
那么
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
实际上我是在使用jquery展示一个Web服务的状态框,然后强制进行postback来刷新ListView。因此,它在提交回来时不会调用Web服务或显示状态框,只有更新后的ListView数据。
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});