我有一个数组值,需要在网页中切片和显示。我有prev
和next
箭头,根据我正在切割数组值的数组导航。当我使用next
箭头时,这是有效的。但不使用prev
数组。
逻辑上我在这里犯了一些错误。当next
或prev
超过数组长度或小于数组长度时,我正在应用opacity
并禁用该按钮。
任何人在这里纠正我的错误?
这是我的代码:
var num = 0;
var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"];
var batch = 5;
var value = 0;
var showArray = function (num) {
var required = myArray.slice(value, (batch+value));
console.log(required, num);
value += 5;
}
showArray(0);
function add(amount) {
num = (num + myArray.length - batch + amount) % myArray.length + batch;
showArray(num);
}
$('#next-arrow').click(function(e){
if(value >= myArray.length) {
$(e.target).css({ opacity:0.5 });
return
}
$(e.target).css({ opacity:1});
add(batch)
});
$('#prev-arrow').click(function(e){
if(value <= myArray.length) {
$(e.target).css({ opacity:0.5 });
return
}
$(e.target).css({ opacity:1});
add(-batch)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<a href="#" id="prev-arrow">Previous</a>
<a href="#" id="next-arrow">Next</a>
</div>
答案 0 :(得分:0)
请尝试这个
$(document).ready(function(){
var num = 0;
var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"];
var batch = 5;
var nextIndex = 0;
var prevIndex = 0;
var showArray = function (boolShowPrev) {
var required;
if(boolShowPrev){
console.log("==",nextIndex, nextIndex+batch);
required = myArray.slice(nextIndex, nextIndex+batch);
console.log(required)
nextIndex += 5;
prevIndex -= 5;
}else{
if(nextIndex >= myArray.length){
prevIndex=batch- (nextIndex-myArray.length);
required = myArray.slice(-prevIndex);
console.log(required);
nextIndex -= 5;
}else{
console.log("prev",-batch-prevIndex,-prevIndex)
required = myArray.slice(-batch-prevIndex,-prevIndex);
console.log(required);
prevIndex +=batch;
nextIndex -= 5;
}
}
}
showArray(true);
$('#next-arrow').click(function(e){
if(nextIndex >= myArray.length) {
$(e.target).css({ opacity:0.5 });
return
}
$(e.target).css({ opacity:1});
showArray(true)
});
$('#prev-arrow').click(function(e){
if(prevIndex >= myArray.length) {
$(e.target).css({ opacity:0.5 });
return
}
$(e.target).css({ opacity:1});
showArray(false)
});
})
请参阅此Plunker