我一直在尝试让 jquery 在我正在构建的 WordPress 主题中运行。如果我对非 worpress 网站使用传统方法,我可以让它工作:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
但我读到这不是在 WordPress 中使用 jquery 的正确方法,因为它可能会导致冲突和其他问题。我已阅读 WordPress Codex 和此网站:http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/这实际上比法典更有帮助。我已经在 StackOverflow 上检查了类似的问题,并尝试了那里列出的解决方案,但 jquery 仍然无法加载。我发现关于这个主题的其他网站不是很清楚。这是我迄今为止在functions.php 文件中的代码,但它仍然无法正常工作:
function jqry_init() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://code.jquery.com/jquery-latest.min.js', false);
wp_enqueue_script('jquery');
}
}
add_action('init', 'jqry_init');
我尝试从 Google 直接从 jquery 加载它,并引用我在网站文件中的 jquery 副本。这些都不起作用。我应该提到,如果这有什么不同的话,我正在本地主机上使用 xampp 完成所有这些工作。我错过了什么?
更新: 以下是我正在运行的片段/其他脚本:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/scripts/isotope.js"></script>
<script type="text/javascript">
JQuery(document).ready(function($) {
var $container = $('#content');
$container.isotope({
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
JQuery('#nav a').click(function($) {
var selector = $(this).attr('data-filter');
$container.isotope({
filter: selector,
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
return false;
});
});
</script>
最佳答案
您想要使用wp_enqueue_scripts
Hook 来添加脚本。您不需要检查管理员,因为管理脚本还有另一个 Hook admin_enqueue_scripts
function jqry_init() {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://code.jquery.com/jquery-latest.min.js', false);
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'jqry_init');
如果您的 jQuery 代码片段仍然无法工作,可能是由于无冲突包装器所致。
例如,如果以下内容不起作用,并且您得到 $ is not defined error
:
$( document ).ready( function() {
//do stuff here
});
您需要将其更改为
jQuery( document ).ready( function( $ ) {
//do stuff here with the $ shorthand
});
更新
在您的 header.php
中
收盘前</head>
标签请确保您有
<?php wp_head();?>
wp_head()
很重要,因为这是将函数添加到 wp_enqueue_scripts
的地方将被运行。没有它,它们将无法运行。
关于jquery - 在 WordPress 中运行 jquery 还需要什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15958224/