由於某種原因,我的變量保持重置爲2,儘管我希望在函數調用時增加變量。這真的很煩人,我重構了代碼幾次無濟於事!它應該是簡單...變量不在jQuery/JS中遞增?
這裏是我的代碼:
(function($) {
$(document).ready(function() {
var count = 2;
var total = <?php echo $loop->max_num_pages; ?>;
if (count <= total) {
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + count + '&loop_file=forums',
success: function(html){
$("#content").append(html);
}
});
count++;
}
});
} else {
return;
}
});
})(jQuery);
編輯:感謝您的答覆迄今!下面更新代碼:
<script type="text/javascript">
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
jQuery(window).scroll(function() {
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()){
console.log('Old value: ' + pageCount);
if (pageCount > total){
return false;
} else {
loadArticle(pageCount);
}
pageCount++;
console.log('New value: ' + pageCount);
}
});
function loadArticle(pageNumber) {
jQuery.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=forums',
success: function(html){
jQuery("#content").append(html);
}
});
return false;
}
</script>
新的值總是3老值始終是2(在控制檯輸出),所以它仍然被重置...
解決:在AJAX方法的HTML回調造成了這個問題。將增量移到那裏工作!新代碼:
(function($) {
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if (pageCount > total){
return false;
} else {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageCount + '&loop_file=forums',
success: function(html){
$("#content").append(html);
pageCount++;
}
});
}
}
});
})(jQuery);
我認爲你的'html'返回的響應包含相同的腳本,使你的變量再次2 –