1

我有以下代码:

 <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 可以单独使用 $。

4

2 回答 2

2

The most probable reason as to why it fails is that $(document).ready() appears before the jQuery script include tag.

How or why it fails will depend upon how you're including the file, but one way to solve this is to use BlogEngine.NET's AddJavaScriptInclude() in the Utils static class and add jQuery in the BlogBasePage class' OnLoad method.

For example,

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);
    }

}

Now jQuery will be included in the <head>. If you have your script in the master page, then I would advise putting it into the <body> to ensure that the jQuery script include will come before your code and avoid the same situation as before; if your script is in another external file, then you could use AddJavaScriptInclude() to include it in the page too, just make sure that it comes after adding the jQuery file.

One other thing to note, it may be sensible to either rename the variable $ in the Blog.js file and any other js files that BlogEngine.NET comes with as you have done, or use jQuery's $.noConflict(); and then wrap your jQuery code inside a self-invoking anonymous function like so

(function($) {

    // I can still use $ here for shortahnd for jQuery.

    $(document).ready(function() {
        // code to run when the DOM has loaded
    });

})(jQuery);

so that you can still use the $ shorthand for jQuery inside of the function.

于 2009-10-24T22:23:24.433 回答
0

我不知道您的示例为什么会失败,但我很确定您只需执行以下操作即可获得 document.ready 行为:

$(function() {

});
于 2009-10-06T16:38:32.423 回答