我在wordpress库中的.js文件中有以下代码:
jQuery.noConflict();
(function($) {
$(document).ready(function(){
var timerLength = 5;
var secs = timerLength;
var currentSeconds = 0
function countdownTimer() {
currentSeconds = secs % 60;
secs--;
if(secs !== -1) setTimeout('countdownTimer()',1000);
console.log(currentSeconds);
if(currentSeconds == "00"){
// Popup shows if the timer runs out
showPopup();
};
};
function checkForCookies() {
cookieValue = $.cookie('solium_product_page_notification');
if ( cookieValue == undefined ){
countdownTimer();
} else if ( cookieValue == "closed" || "dont-show-again" ) {
console.log('Cookies are blocking the popup');
};
};
function showPopup() {
$("#productModal").modal("show");
setCookies();
};
function setCookies(){
$("#close-only").on("click", function(){
$.cookie('solium_product_page_notification','closed', { expires: 1 }); // Cookie expires in 1 day
console.log('Temp Cookie Created');
});
$("#dont-show-again").on("click", function(){
$.removeCookie('solium_product_page_notification','closed');
$.cookie('solium_product_page_notification','dont-show-again', { expires: 365 }); // Cookie expires in 1 year
console.log('Perm Cookie Created');
});
};
checkForCookies();
});
})(jQuery);
并在footer.php中调用它:
if( 'product' === get_post_type() ) {
if ( wp_script_is( 'jquery', 'done' ) ) {
?>
<!-- PRODUCT PAGE MODAL -->
<!-- BEGIN MODAL -->
<div class="modal fade" id="productModal" data-keyboard="false" >
<div class="modal-body">
<button type="button" class="close" id="close-only" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Hey there!</h4>
<p class="popup-text">While you were looking around, we found a few things you may be interested in!</p>
<button type="button" class="plain-link" id="dont-show-again" data-dismiss="modal">Dont Show Again</button>
</div>
</div>
<!-- END MODAL -->
<script type="text/javascript" src="<?php echo esc_url( get_template_directory_uri() ); ?>/assets/js/product-modal.js"></script>
<?php
};
};
现在当页面加载它时会进行cookie检查,然后它开始倒计时,它会控制台记录5但是一旦计数到4,我就会在Chrome中收到“VM1850:1未捕获的ReferenceError:countdownTimer未定义”。
但是,如果我以面向对象的方式定义倒计时时间
countdownTimer = function() {
currentSeconds = secs % 60;
secs--;
if(secs !== -1) setTimeout('countdownTimer()',1000);
console.log(currentSeconds);
if(currentSeconds == "00"){
// Popup shows if the timer runs out
showPopup();
};
};
一切正常!有没有人知道为什么会这样?我想知道jQuery noconflict是否导致问题,因为所有这些代码都包含在一个函数中。任何帮助将不胜感激!
答案 0 :(得分:2)
因为函数是在文档就绪块中定义的,所以你在setTimeout中的全局作用域上调用它。
(?!\\A)
需要
if(secs !== -1) setTimeout('countdownTimer()',1000); //executes on window, not the current scope