它失败的最可能原因是$(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 将包含在 <head> 中。如果您在母版页中有您的脚本,那么我建议将其放入 <body> 以确保 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。