简体   繁体   English

在ascx.cs用户控件中执行JavaScript

[英]Execute javascript in an ascx.cs usercontrol

I'm dynamically adding controls to my ascx.cs usercontrol and therefore I also need to dynamically execute javascript code from my ascx.cs usercontrol. 我正在将控件动态添加到我的ascx.cs用户控件中,因此,我还需要从我的ascx.cs用户控件中动态执行JavaScript代码。

I'm executing my javascript using: 我正在使用以下代码执行我的JavaScript:

Page.ClientScript.RegisterStartupScript(typeof(Page), "reOpen", "<script type='text/javascript'> reOpenClick(); </script>")

This is my javascript in the ascx file 这是我的ascx文件中的javascript

<%@ Register Assembly="obout_Window_NET" Namespace="OboutInc.Window" TagPrefix="obout" %>

<obout:Window runat="server" ID="ow_dialog" Width="200" Height="50"
    Title="Open" IsModal="true" ShowCloseButton="true"
    StyleFolder="~/Styles/obout/window/grandgray" VisibleOnLoad="false">    
   .
   .
   .
   .
</obout:Window>

<script type="text/javascript">

    function reOpenClick() {
        ow_dialog.setTitle("Open");
        ow_dialog.screenCenter();
        ow_dialog.Open();
    }

</script>

When running the code as usual I'm getting the error ReferenceError: ow_dialog is not defined . 当照常运行代码时,出现错误ReferenceError: ow_dialog is not defined But when typing reOpenClick() into the web browser's console everything runs fine. 但是,当在网络浏览器的控制台中键入reOpenClick()时,一切运行正常。

Why am I getting the ReferenceError: ow_dialog is not defined when typing in the function in the console works fine? 为什么在控制台中键入该功能正常时,为什么出现ReferenceError: ow_dialog is not defined

Add script tags to the markup 将脚本标签添加到标记

<script type="text/javascript">
   // place your javascript here
</script>


<script type="text/javascript" href="path to js file" />

or 要么

In the load event of your control, do something like this: 在控件的load事件中,执行以下操作:

if (!Page.ClientScript.IsClientScriptIncludeRegistered("keyName"))
    Page.ClientScript.RegisterClientScriptInclude("keyName",
        Page.ResolveUrl("~/Scripts/jsfile.js"));

If the user control is in an UpdatePanel and/or its Visible attribute is set to false by default, you will get "Object expected" error because simply your script is not loaded when the page loads and the function you are calling is non-existent. 如果用户控件位于UpdatePanel和/或默认情况下将其Visible属性设置为false,则将收到"Object expected"错误,因为仅在页面加载时加载脚本,并且所调用的函数不存在。

Workaround for this is to use style="display:none" instead of Visible="false" for your user control in the main page. 解决方法这是使用style="display:none" ,而不是Visible="false"主页的用户控件。

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

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