【问题标题】:Loading jQuery from ASP.NET User Control ascx page?从 ASP.NET 用户控件 ascx 页面加载 jQuery?
【发布时间】:2013-07-01 12:58:45
【问题描述】:

你能把 jQuery 代码放在 .ascx 页面中吗?

我有一个在 ASP.NET 项目中使用的用户控件。当我在 default.aspx 页面上选择某些内容时,会动态创建该控件的多个实例。我想用 jQuery 操作部分用户控件。但是,jQuery 似乎没有加载。

我在我的 MasterPage 中引用了 jQuery 库。我从我的 default.aspx 测试了以下代码并且它可以工作,但是当我在我的 ascx 页面中使用相同的代码时我没有得到任何响应:

<script type="text/javascript" charset="utf-8">
    if (typeof ($) != 'function') alert('This component requires jQuery.');
    else $(function () { alert('The DOM is ready for jQuery manipulation.'); });
</script>

有什么想法吗?

谢谢。

【问题讨论】:

    标签: jquery asp.net


    【解决方案1】:

    如果您在母版页中引用了 jQuery,那么您可以在 .ascx 中访问它。

    你能把它放在 $(document).ready(function(){ /* 你的代码.. */ }); -in ascx- 并检查?

    【讨论】:

      【解决方案2】:

      要在用户控件 .ascx 中包含和运行 JavaScript 或 JQuery 代码行,不应在 HTML 代码中插入 &lt;script&gt; 标记。如果需要,仅使用它来插入对 JQuery 文件的引用。 ASP.NET 页面事件(例如 Load 或 UpdatePanel 用户控件)不一定会触发客户端事件,例如在 .aspx 页面上完成加载时。为此,您应该使用 ScriptManager.RegisterClientScriptBlock。要成功使用您的示例,请在 .ASCX 控件的 Load 事件中设置此代码:

      ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ActivateJsSample", 
      @"<script type = 'text/javascript'>
      if (typeof ($) != 'function') alert('This component requires jQuery.');
      else $(function () { alert('The DOM is ready for jQuery manipulation.'); });
      });
      </script>", false);
      

      这将与用户控件的 Load 事件同步并触发,并且每次都会触发。

      【讨论】:

        猜你喜欢
        • 2011-01-13
        • 2012-11-11
        • 1970-01-01
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2013-09-08
        • 2012-05-14
        • 2012-08-16
        相关资源
        最近更新 更多