【发布时间】:2020-08-31 11:16:56
【问题描述】:
我将 PHP 会话传递给要在 Jquery 代码中使用的变量。下面,我在四个区域调用控制台日志。控制台日志编号 1 和 3 反映的变量值没有问题。 2和4没有。我需要 #4 具有价值,以便我可以在条件中使用变量。我想这可能是范围问题,但我不明白为什么。寻求一些指导。
<script type="text/javascript">
// GET VARIABLES THROUGH PHP SESSSION
customerType = '<?php echo $customerType; ?>';
myClicks = '<?php echo $myClicks; ?>';
email = '<?php echo $email; ?>';
console.log('1 ' + email);
console.log('1 ' + myClicks);
console.log('1 ' + customerType);
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
$(document).ready(function () {
rowsPerPage = 5;
// GETTING DATA FROM FUNCTION BELOW
getData();
$('#load-more').click(function () {
console.log('2 ' + email);
console.log('2 ' + myClicks);
console.log('2 ' + customerType);
$('#load-more').html('Loading...');
var rowID = Number($('#row-id').val());
var allCount = Number($('#count').val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$('#row-id').val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
});
/* REQUEST DATA */
function getData () {
console.log('3 ' + email);
console.log('3 ' + myClicks);
console.log('3 ' + customerType);
var rowID = $('#row-id').val();
var allCount = $('#count').val();
$.ajax({
url: 'promotions/newest-load-button-data.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function (response) {
setTimeout(function () {
loadData(response);
$('#load-more').html('Load More');
}, 1000);
}
});
}
/* LOAD DATA TO PAGE */
function loadData (data) {
console.log('4 ' + email);
console.log('4 ' + myClicks);
console.log('4 ' + customerType);
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$('#count').val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoName = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
// Here I will use conditions based on email, customerType, and myClicks
if (promoType == 'Banner') {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoName + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == 'Video Banner') {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoName + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
$('#load-more').html('Load More');
}
}
});
</script>
【问题讨论】:
-
没有 HTML 数据很难说。您在点击事件上有 2 个,但我们没有。我会通过 sn-p 放置一个最小的工作示例供我们诊断。 :)
-
可能是范围问题。尝试将
function loadData()移动到全局范围(与customerType相同的范围)。命名函数会被提升,匿名函数不会。 -
绝对范围。
标签: javascript jquery scope