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)中调用函数,并添加了方法:RegisterStartupScriptRegisterStartupScriptShowMessage

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

问题是当我调用ShowMessage包含脚本代码行的方法时它不起作用。但是当我运行脚本代码行时,它就可以工作了;问题是为什么它不运行ShowMessage

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

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

1 回答 1

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);
于 2017-09-23T20:26:52.617 回答