我知道有关此主题的问题已经提交了很多,但已经困扰了我几个小时。我无法让jQuery与WordPress一起使用。我已经检查并仔细检查并阅读了无数文章。任何帮助或建议都将非常受欢迎。
我只是刚开始在一个新的WordPress网站上,所以插件很少。
我正在使用主题:27和一个基于此的子主题。
在我正在使用的测试页上,在控制台中,我看到“ Uncaught ReferenceError:未定义jQuery”
这是我的代码:
该脚本文件称为testjQuery.js。内容是:
jQuery(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
子主题functions.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' );
我正在使用带有“测试模板”的PAGE。这里是内容:
<?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添加到我的网站,所以我确定我犯了一个初学者错误-我是一个初学者。
答案 0 :(得分:2)
您的页面模板应包含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()。
答案 1 :(得分:0)
只需使用 $ 作为函数参数将$定义为jQuery
jQuery(document).ready(function($) {
$("p").click(function(){
$(this).hide();
});
});
否则,您可以尝试以下代码:
(function($){
$("p").click(function(){
$(this).hide();
});
});