即使其他加载的jQuery函数正在运行,自定义jQuery函数也无法在WordPress上运行

我正在使用WordPress 3.8.1。 我想使用此函数来使用粘性标头

 $(document).ready(function() { var $header = $("header"), $clone = $header.before($header.clone().addClass("clone")); $(window).on("scroll", function() { var fromTop = $(window).scrollTop(); console.log(fromTop); $("body").toggleClass("down", (fromTop > 200)); }); });  

但它不适合我,我不知道为什么。 我知道jQuery是与我的WordPress共享的,因为Flexslider 2现在工作正常。

添加这个:

 var j = jQuery.noConflict(); 

现在你可以编写你的jQuery代码:

 j(document).ready(function(){ j('.class').event(function(){ // your action............ }); }); 

只需将noConflict()函数赋值给变量,并在jQuery代码中使用该变量而不是$ noConflict()

不要在脚本中运行jquery。 这将打破wordpress中的其他脚本。

创建一个.js文件并将其包含在您的functions.php文件中。

 */** * Proper way to enqueue scripts and styles */ function theme_name_scripts() { wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );* 

然后在.js文件中将代码包装在No Conflict包装器中。 否则,使用$()将返回undefined。

 jQuery(document).ready(function($) { var $header = $("header"), $clone = $header.before($header.clone().addClass("clone")); $(window).on("scroll", function() { var fromTop = $(window).scrollTop(); console.log(fromTop); $("body").toggleClass("down", (fromTop > 200)); }); }); 

您是否尝试在标题中设置jquery文件(假设您的模板文件夹中有jquery文件,但它可以在任何地方,只要您正确引用它):

  

 $(document).ready(function(){ $("#container").alert("blah"); $(".goodshelf_ul li:first").css("border-top: none;"); $(".custom_ul li:first").addClass("first"); $("#footer .frame:last").css("margin: 0;"); $("#footer .frame:last").addClass("last"); }); 

我在我的所有wordpress网站上使用jquery,它的工作正常,希望这会有所帮助。

迟到了这里的派对,但正确的解决办法是:

理解在WordPress中,jQuery是在无冲突模式下加载的。 这意味着$ variable 引用jQuery。

但是,通过修改脚本以使用准备好的无冲突安全文档,您可以在函数中使用$

修改脚本如下:

 // original code - doesn't work, because $ is not jQuery in WordPress // $(document).ready(function() { // shorthand no-conflict-safe document ready: jQuery(function($) { // Now $ is safe to use - it references jQuery within this doc ready function var $header = $("header"), $clone = $header.before($header.clone().addClass("clone")); $(window).on("scroll", function() { var fromTop = $(window).scrollTop(); console.log(fromTop); $("body").toggleClass("down", (fromTop > 200)); }); });