Wordpress 中的 jQuery - 无法解决问题:"Uncaught ReferenceError: jQuery is not defined"



我知道这个主题已经提交了很多问题,但我已经被困了好几个小时了。我无法让jQuery与WordPress一起工作。我已经反复检查并阅读了无数关于这方面的文章。欢迎提供任何帮助或建议。

  • 我刚刚开始使用一个新的WordPress网站,所以插件很少。

  • 我使用的主题是:二十岁和一个基于此的儿童主题。

在我使用的测试页面上,在控制台中,我看到了"Uncaught ReferenceError:jQuery is not defined">

这是我的代码:

脚本文件名为testjQuery.js。内容为:

jQuery(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});

子主题函数.php文件的内容为:

function add_my_script() {
wp_enqueue_script('testjQuery', home_url() . '/wp-content/themes/twentyseventeen-child/resources/js/testjQuery.js', array('jquery'));
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

我使用的是一个带有"测试模板"的页面。以下是内容:

<?php 
/* 
Template Name: temp_jQuery
Template Post Type: Page
/?>
<head>
<script type='text/javascript' src='https://stunninghikes.com/evenbetterhikes/wp-content/themes/twentyseventeen-child/resources/js/testjQuery.js'></script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>

我试过各种各样的组合,把什么放在哪里。没有快乐。这是我第一次尝试将jQuery添加到我的网站,所以我确信我犯了一个初学者错误——我是一个初学者。

在页面内容开始之前,页面模板应该包含get_header();函数。如果您不想在此模板中包含页眉,那么页面顶部应该包含一个wp_head();函数。

发生jQuery错误是因为您没有在此模板中包含jQuery.js库。wp_head()包含要包含在页面中的所有必需的JS和CSS库。

<?php 
/* 
* Template Name: temp_jQuery
* Template Post Type: Page
*/
?>
<head>
<script type='text/javascript' src='https://stunninghikes.com/evenbetterhikes/wp-content/themes/twentyseventeen-child/resources/js/testjQuery.js'></script>
<?php 
get_header(); 
/* OR */ 
wp_head();
?>    
</head>

<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>

<?php get_footer(); ?> 

此外,如果在此模板上未包含页脚,则必须在模板底部包含get_footer();,或在页面底部包含wp_footer();

只需使用$作为函数参数,即可将$定义为jQuery

jQuery(document).ready(function($) {
$("p").click(function(){
$(this).hide();
});
});

或者你可以试试下面的代码:

(function($){
$("p").click(function(){
$(this).hide();
});
});

最新更新