简体   繁体   English

如何动态不呈现脚本标记?

[英]How to dynamically not render a script tag?

I want to be able to dynamically (on page load) decide to set it to Visible=false so it won't be rendered. 我希望能够动态地(在页面加载时)决定将其设置为Visible=false以便它不会被渲染。 I tried runat=server but that's only for virtual paths. 我试过runat=server但这只适用于虚拟路径。

You can use ClientScriptManager.RegisterClientScriptBlock or ClientScriptManager.RegisterStartupScript to conditionally add the script. 您可以使用ClientScriptManager.RegisterClientScriptBlockClientScriptManager.RegisterStartupScript来有条件地添加脚本。

if (condition)
{    
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();
    StringBuilder cstext2 = new StringBuilder();
    cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
    cstext2.Append("Form1.Message.value='Text from client script.'} </");
    cstext2.Append("script>");
    cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}

If you have script that is not small then you can put the script in some js file and use ClientScriptManager.RegisterClientScriptInclude 如果您的脚本不小,那么您可以将脚本放在某些js文件中并使用ClientScriptManager.RegisterClientScriptInclude

if (condition)
{
    ClientScriptManager cs = Page.ClientScript;
    cs.RegisterClientScriptInclude("ScriptKey", "ScriptURLToInclude");
}

In the ASP.NET markup language you can steer the rendering of any arbitrary contents. 在ASP.NET标记语言中,您可以控制任何内容的呈现。 That is rendering a script tag only under certain conditions should be as simple as: 那就是在某些条件下渲染脚本标记应该简单如下:

<% if (shouldRenderScriptTag) { %>
    <script src="..." />
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM