I have the following code:
<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() {
});
The page fails on load with "Object expected". If I hover over $(document) in Visual Studio, it expands to show its properties. There is no other object here, so unless it's failing within the jquery library, what else could be causing this?
There shouldn't be any collisions happening with the BlogEngine script either. I renamed all of the $ variables to $BE in blog.js, so JQuery gets sole use of $.
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.
I don't know why your example fails, but I'm pretty sure you can get the document.ready behvaiour just by doing:
$(function() {
});
精彩评论