【发布时间】:2018-05-31 11:50:42
【问题描述】:
所以我尝试了一段时间将我的 jQuery 脚本(一个插件,一个自己编写)包含到我的自定义 wordpress 主题中。尽管阅读了很多关于如何正确包含它们的信息,但我还是无法让它发挥作用。 所以我有一个插件脚本(jQuery.fullPage.js)和一个自定义编写的(main.js),它们(both!)放置在“assets/scripts/”目录中。
如说明中所述,我在 functions.php 中注册它们:
function load_theme_scripts() {
wp_register_style('fullPageStyle', get_template_directory_uri() . '/custom-css/jquery.fullPage.css');
wp_enqueue_style( 'fullPageStyle');
wp_register_script( 'theFullPage', get_template_directory_uri() . '/assets/scripts/jquery.fullPage.js', array('jquery'), false, true );
wp_enqueue_script( 'theFullPage');
wp_register_script( 'mainScript', get_template_directory_uri() . '/assets/scripts/main.js', array( 'jquery' ), '1.0.0', true );
wp_enqueue_script( 'mainScript');
}
add_action( 'wp_enqueue_scripts', 'load_theme_scripts' );`
只有这段代码什么都没有发生。经过一番阅读,我发现(不知道这是否是正确的方法)我也必须在 html 代码的<head> 中调用脚本。
所以在我的 home.html 的<head>中,我现在有以下代码:
<head>
<title><?php wp_title()?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
<script type='text/javascript' src='http://localhost/portfolio_wordpress/wp-content/themes/myportfolio/assets/scripts/jquery.fullPage.js'></script>
<script type='text/javascript' src='http://localhost/portfolio_wordpress/wp-content/themes/myportfolio/assets/scripts/main.js'></script>
<?php wp_head(); ?>
</head>
现在调用脚本(如果某事不符合最佳实践,请纠正我!)但我在 main.js 中收到错误:Can't find variable: $。我想这可能是因为 jQuery 在 wordpress 中的兼容模式,所以用jQuery替换$,但错误是Can't find variable: jQuery。
带有$的main.js代码:
$(document).ready(function() {
alert("Main script is workin!");
$('#fullpage').fullpage({
scrollingSpeed: 1000
});
alert("Main script is workin!");
});
main.js 用jQuery代替:
jQuery(document).ready(function($) {
alert("Main script is workin!");
$('#fullpage').fullpage({
scrollingSpeed: 1000
});
alert("Main script is workin!");
});
请帮帮我,这真的让我发疯了!由于我刚开始为 wp 编写自定义主题,因此非常欢迎以更好或更简洁的方式编写此功能的提示!
【问题讨论】:
-
get_template_directory_uri() 从模板文件夹中获取。和 plugins_url( '/js/custom-script.js', FILE ) 来自插件文件夹
标签: jquery wordpress wordpress-theming