1

我在下面粘贴了工作代码,其中有一个名为 FormatStatus() 的函数作为内联代码的一部分,实际定义在后面的代码中(C#)。我的问题是如果我将函数 (FormatStatus()) 移动到外部 javascript 文件中,我如何从内联代码中调用它。

 <asp:Label ID="lblSts" runat="server" Text= '<%# FormatStatus(Eval("StsId").ToString()) %>' >                                        
          </asp:Label>

我背后的代码:

    protected string FormatStatus(string Id)
    {
        string formatText = string.Empty;

        switch (int.Parse(Id))
        {
            case 0:
                formatText = "New";
                break;
            case 1:
                formatText = "Old";
                break;
          ..... 
        }

        return formatText;
    }
4

2 回答 2

1

JavaScript 函数只能被任何事件调用。如果你想运行 js 函数作为初始方法,你可以使用 window.onload。因此,您可以在页面中创建全局 javascript 数组,并在代码后面使用来自 c# 的 id 值填充它,并在 window.load 上调用 formatStatus:

if (!Page.ClientScript.IsStartupScriptRegistered("preloadArray" + this.ClientID))
{
      string script = "<script type='text/javascript'> ";
      for (int i = 0; i < ...; i++)
      {
           script += "arr.push("+i.ToString()+");";
      }
      script += "formatStatus('" + gvAdminActiveAsgnments.ClientID + "');";            
      script += "</script>";

      Page.ClientScript.RegisterStartupScript(this.GetType(),
            "preloadArray" + this.ClientID, script);
 }

(您可以使用 Page_Load 或 ItemDataBound 处理程序)

然后你应该编写函数,它接受一个带有网格 id 的参数:

function formatStatus(id){
 var table = document.getElementById(id);
 var rows = table.getElementsByTag('TR');
 for(var i=0; i<rows.length;i++){
   //puts into label from table row result for arr[i]
 }
}

它将在您的表的页面加载时调用,该表将从 asp:GridView 呈现。您可以将 formatStatus 绑定到任何事件,例如单击某个按钮。所以,它会改变标签。

于 2011-10-07T00:37:37.757 回答
1

您可以尝试这样做,只需确保在文档顶部包含外部 js 文件。

 <asp:Label ID="lblSts" runat="server">
      <script type="text/javascript">
            document.write(FormatStatus('<%# Eval("StsId").ToString() %>');
      </script>                                       
 </asp:Label>
于 2011-10-07T01:51:39.083 回答