【问题标题】:Object Expected using JQuery with BlogEngine.net使用 JQuery 和 BlogEngine.net 的预期对象
【发布时间】:2009-10-06 16:34:58
【问题描述】:

我有以下代码:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
    });

页面加载失败并显示“预期对象”。如果我在 Visual Studio 中将鼠标悬停在 $(document) 上,它会展开以显示其属性。这里没有其他对象,所以除非它在 ​​jquery 库中失败,否则还有什么可能导致这种情况?

BlogEngine 脚本也不应该发生任何冲突。我在 blog.js 中将所有 $ 变量重命名为 $BE,因此 JQuery 可以单独使用 $。

【问题讨论】:

    标签: jquery object blogengine.net


    【解决方案1】:

    它失败的最可能原因是$(document).ready()出现在jQuery脚本包含标签之前。

    失败的方式或原因取决于您如何包含文件,但解决此问题的一种方法是在 Utils 静态类中使用 BlogEngine.NET 的 AddJavaScriptInclude() 并在 BlogBasePage 类中添加 jQuery ' OnLoad 方法。

    例如,

    public abstract class BlogBasePage : System.Web.UI.Page
    {
        /* other BlogBasePage methods, properties, fileds, etc */
    
        /// <summary>
        /// Adds links and javascript to the HTML header tag.
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            /* other BlogEngine.NET code ... */
    
            // add jQuery to html <head> section. I've put my scripts
            // in a folder named 'scripts'
            AddJavaScriptInclude(Utils.RelativeWebRoot + "scripts/jquery-1.3.2.min.js", false, false);
        }
    
    }
    

    现在 jQuery 将包含在 &lt;head&gt; 中。如果您在母版页中有您的脚本,那么我建议将其放入 &lt;body&gt; 以确保 jQuery 脚本包含将出现在您的代码之前并避免与以前相同的情况;如果您的脚本在另一个外部文件中,那么您也可以使用AddJavaScriptInclude() 将其包含在页面中,只需确保它在添加 jQuery 文件之后出现。

    另外需要注意的是,在 Blog.js 文件和 BlogEngine.NET 附带的任何其他 js 文件中重命名变量 $ 可能是明智的,或者使用 jQuery 的 $.noConflict(); 和然后将您的 jQuery 代码包装在一个像这样的自调用匿名函数中

    (function($) {
    
        // I can still use $ here for shortahnd for jQuery.
    
        $(document).ready(function() {
            // code to run when the DOM has loaded
        });
    
    })(jQuery);
    

    这样您仍然可以在函数内部使用 $ 简写 jQuery。

    【讨论】:

      【解决方案2】:

      我不知道您的示例为什么会失败,但我很确定您可以通过以下方式获得 document.ready 行为:

      $(function() {
      
      });
      

      【讨论】:

      • $(fn) 只是$.ready 的简写,与他的问题无关。由于可读性较差,这也是许多人避免使用的一种。
      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2020-03-04
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多