从后面的代码调用Javascript方法

时间:2013-03-18 10:43:27

标签: c# javascript asp.net code-behind

我在Javascript中有一个函数,它使标签不可见。我想从后面的代码中调用这个函数。我无法让它隐形。以下是两行代码。

C#代码背后:

          Page.ClientScript.RegisterStartupScript(GetType(), "MyFunction", "MyFunction();", true);

的javascript:

         <script type ="text/javascript" language="javascript">
          function MyFunction()
          {
                 document.getElementById("Label8").style.display = 'none';

          }
          </script>

如果有任何错误,请告诉我。看起来控件不仅仅是方法定义。

谢谢

2 个答案:

答案 0 :(得分:2)

ClientID中使用getElementById服务器控件(标签)或将ClientIDMode设置为static for label并确保html元素的可用性为脚本,因为您可以放置​​脚本标记就在{em>关闭标签body

之前
<script type ="text/javascript" language="javascript">
      function MyFunction()
      {
          document.getElementById("<%= Label8.ClientID %>").style.display = 'none';    
      }
</script>

答案 1 :(得分:1)

我认为你的网页上有这样的标签;

<asp:Label ID="lblExample" runat="server" ClientIDMode="Static" Text="Hello"></asp:Label>

然后我建议你使用jQuery,你的js函数应该是这样的;

<script type ="text/javascript" language="javascript">
   function hideLabel() 
   {
     $("#lblExample").hide();
   }
</script>

最后在你的代码中调用你的js函数;

 ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.ToString(), "hideLabel();", true);

如果您使用ScriptManagerMasterPage,请按此方式调用;

 ScriptManager.RegisterStartupScript(this,this.GetType(), DateTime.Now.ToString(), "hideLabel();", true);
相关问题