2017-09-23 27 views
0

我在的.aspx页面(HTML标记)有一个脚本工作:脚本代码不与方法

<div id="alert"> 
    <asp:Label ID="lblAlert" style="font-size: xx-large" runat="server"></asp:Label> 
</div> 
<!-- /.alert --> 

<script> 

    function AutoHideAlert(v) { 
     var al = document.getElementById('<%=lblAlert.ClientID%>'); 

     al.innerText = v; 

     $("#alert").fadeTo(3500, 500).slideUp(1500, function() { 
      $("#alert").slideUp(500); 
     }); 
    } 

</script> 

我打电话aspx.cs文件AutoHideAlert(v)功能(代码-Behind)使用RegisterStartupScript和我在ShowMessage方法添加RegisterStartupScript

private void ShowMessage(string msg) 
{ 
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('"+msg+"');", true); 
} 

问题是,当我打电话ShowMessage我包含脚本代码行的thod不工作。但是当我运行脚本代码行然后它的工作;问题是为什么它不与ShowMessage一起运行?

编辑1:从@ M4N的评论,我试图通过设置第三个参数"Alert Message"但它仍然无法正常工作。

private void ShowMessage(string msg) 
{ 
    ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message", "AutoHideAlert('"+msg+"');", true); 
} 
+0

你试过将'key'参数(第三个参数)设置为某个值? – M4N

回答

1

我想ScriptManager.RegisterStartupScript在生成脚本之前生成脚本。由于JS在目前浏览器中执行读取,所以在执行AutoHideAlert的那一刻,如果不存在尚未 尝试使用$(document).ready是你的JQuery

ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message", 
    "$(document).ready(function(){ AutoHideAlert('"+msg+"'); }", true); 

或者document.addEventListener('DOMContentLoaded'不JQuery的

ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message", 
    "document.addEventListener('DOMContentLoaded', 
           function(){ AutoHideAlert('"+msg+"'); })", true); 
+1

如何使用方法? – AsifAli72090

+0

有2个使用JQuery和没有的例子,Ido不知道你是否有JQuery这就是为什么我给你两个 – ASpirin

+0

问题没有解决,但我已upvoted :( – AsifAli72090