我觉得我肯定错过了一些简单的东西......但是对于我的生活,找不到我所缺少的东西。
我是将jQuery函数直接包含在header.php文件中的“坏习惯”(以及其他部分)。根据我的理解,这是不赞成的,并且函数应该使用wp_enqueue函数保存在单独的文件中以加载它们(如果我正确地得到它)。
我正在尝试遵循此处给出的解决方案: How do I add a simple jQuery script to WordPress?
我在header.php中有这个简单的函数,应该在文档就绪时启动:
<script>
// Scroll to Top
jQuery(document).ready(function () {
// Force element to hidden state when page loads
jQuery('.scroll-to-top').hide();
// Check to see if the window is top if not then display button
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 200) {
jQuery('.scroll-to-top').fadeIn();
} else {
jQuery('.scroll-to-top').fadeOut();
}
});
//Click event to scroll to top
jQuery('.scroll-to-top').click(function () {
jQuery('html, body').animate({ scrollTop: 0 }, 800);
return false;
});
});
</script>
所以为了“正确”做事,我把我的代码拿出来放在myScripts.js中(当然要删除脚本标签)。在我的functions.php文件中,我添加了以下代码:
<?php
function add_my_script() {
wp_enqueue_script(
'myScripts', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/myScripts.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>
但是当我加载页面时,脚本不再起作用了。
修改
感谢您的帮助到目前为止......更改此行:
add_action( 'wp_enqueue_scripts', 'myScripts' );
到此:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
解决了页面上看到的错误。
不幸的是,代码似乎不再在页面上启动了。我假设因为它是(文档).ready它应该自动触发(就像我直接包含它时一样),但是当我以这种方式包含脚本时它不会。呃......想法?
答案 0 :(得分:2)
请参阅wp_enqueue_script Documentation
wp_enqueue_script($ handle,$ src,$ deps,$ ver,$ in_footer)是正确的函数。
您的第一个参数需要是回调函数名称。