【发布时间】:2016-02-05 04:11:13
【问题描述】:
我正在尝试在我的 wordpress 网站上包含来自 github (https://github.com/rendro/countdown) 正确方式的插件。经过数小时的法典和堆栈研究后,我仍然找不到使其工作的方法。
如果我使用默认方法:
1) 将这些行添加到我的header.php 文件的<head> 中:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/path/to/jquery.countdown.js"></script>
2) 在我的header.php 文件中的</head> 和<body> 之间使用我想要的配置初始化插件,在这种情况下:
<script>
$(function() {
var endDate = "November 30, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
3) 然后在我的html文件中调用插件:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
完美运行!
但是,如果我尝试以正确的方式进行操作
(如果我理解得很好,wordpress 默认附带 jQuery,通过使用默认方法我让用户下载 jquery 两次,这也增加了我的加载时间,对吧?)
这意味着将 jquery 排入队列,然后将我的脚本放入我的 functions.php 文件中,如下所示:
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
然后重复默认方法的步骤2)和3),它根本不起作用!我尝试在步骤 2) 中包装我的 jquery 代码,就像这样:
jQuery(document).ready(function( $ ) {
// $ Works! You can test it with next line if you like
// console.log($);
});
但它仍然不起作用。 如果有人可以提供帮助,将不胜感激!
我目前在我的header.php:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
我目前在我的footer.php:
<script type="text/javascript">
$(function() {
var endDate = "November 14, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
我目前在我的functions.php 中拥有的内容:
// Loads JavaScript file with functionality specific to LCQC.
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
The jquery plugin (.js)
【问题讨论】:
-
head中的脚本会使网站变慢。最好在结束正文标记之前使用脚本。这样所有的内容都被加载了。完成后,将加载 javascript。这样用户已经看到了一些东西。 -
我的脚本标签位于
</head>和<body>标签之间,而不是<head>。不过,谢谢你的这个小建议。我会确保修改它! -
怎么不工作了?控制台有错误吗?
-
我遇到了诸如“Uncaught TypeError: $ is not a function”之类的错误。但我终于让它工作了,我的错误主要是我把我的函数放在了我的function.php文件中。
标签: php jquery wordpress github plugins