【问题标题】:jQuery Handlers Not Working in Word PressjQuery 处理程序在 Wordpress 中不起作用
【发布时间】:2020-10-14 22:00:37
【问题描述】:

**编辑 - 我从头文件中删除了代码并尝试了来自https://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/的说明

我在函数文件中添加了这段代码

function shapeSpace_include_custom_jquery() {

    wp_deregister_script('jquery');
    wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);

}
add_action('wp_enqueue_scripts', 'shapeSpace_include_custom_jquery');

我在控制台中看到对 CDN 的成功 GET 请求。我还尝试将链接从官方 jquery 站点更改为 https://code.jquery.com/jquery-3.5.1.js

我有一个名为 main.js 的文件,其中包含此代码 -

(function ($) {
  console.log("working");

  $(".about-text").click(function () {
    alert("test")
  });

})(jQuery);

“工作”控制台日志显示,因此它知道已加载,但单击的 jQuery 处理程序没有。我也尝试过 hover() 但这不起作用,也尝试过 -

$(".about-text).hide() 

这是我正在测试的 div -

    <div class="about-text">
        <h2><?php the_title(); ?></h2>
        <h3><?php the_content(); ?></h3>
    </div>

我也加了


<div id="target">
  Click here
</div>

和

$( "#target" ).click(function() {
  alert( "Handler for .click() called." );
});

(来自 jquery.com 网站的示例)但它不起作用。

我在这里做错了什么?

【问题讨论】:

  • 你有阻止alert()的内容拦截器吗?尝试使用console.log,也尝试使用$("body").on("click",".about-text",function(){
  • 试过了,还是不行
  • 试试jQuery(document).ready(function($) { $( "#target" ).click(function() { alert( "Handler for .click() called." ); }); }
  • 成功了!谢谢你。你知道原因吗?
  • 添加到我的答案中;)

标签: jquery wordpress


【解决方案1】:

在 WordPress 中,jQuery 是在无冲突模式下加载的,所以你不能像那样使用 $,而是可以使用 jQuery,如下所示,然后你可以使用 $

jQuery(document).ready(function($) {  
    $( "#target" ).click(function() {   
       alert( "Handler for .click() called." ); 
    });   
}

或者你有另一个选择使用no conflict like

var j = jQuery.noConflict();
    j(document).ready(function() {  
        j( "#target" ).click(function() {   
           alert( "Handler for .click() called." ); 
        });   
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多