gpt4 book ai didi

Javascript (Jquery), increment/decrement++/-- operator 计算错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:29 25 4
gpt4 key购买 nike

我正在用左右两个按钮制作幻灯片,当单击按钮时,图像 src 发生变化,新图像出现。图像的位置存储在一个数组中,++ 运算符用于将照片移动到下一张,-- 用于上一张有时它不起作用我必须双击按钮工作。为什么会这样?


HTML

<div class="row">
<div class="col-xs-1">
<a href="" id="left"><img src="images/left.png" width="80px" height="80px"></a>
</div>
<div class="col-xs-6">
<img src="images/1.jpg" id="image">
</div>
<div class="col-xs-1">
<a href="" id="right"><img src="images/right.png" width="80px" height="80px"></a>
</div>
</div>

查询

var count = 1;

var imagesLocation = ['images/1.jpg',
'images/2.jpg',
'images/3.jpg',
'images/4.jpg',
'images/5.jpg'];

$('#right').on('click',function(e){
e.preventDefault();
if(count < 6){
$('#image').attr('src',imagesLocation[count]);
count++;
}
});

$('#left').on('click',function(e){
e.preventDefault();
count--;
$('#image').attr('src',imagesLocation[count]);

});

最佳答案

数组索引从 0 开始,而不是 1

var count = 0;
//----------^--- update here

var imagesLocation = ['images/1.jpg',
'images/2.jpg',
'images/3.jpg',
'images/4.jpg',
'images/5.jpg'
];

$('#right').on('click', function(e) {
e.preventDefault();
if (count < imagesLocation.length) {
//--------^----- .length can be use instead, so this will work even if array size changed
$('#image').attr('src', imagesLocation[++count]);
//-------------------------------------^-- ++count will increment the count, then returns the incremented count value
}
});

$('#left').on('click', function(e) {
e.preventDefault();
if (count > 0) {
//------^---- to avoid negative index
$('#image').attr('src', imagesLocation[--count]);
//-------------------------------------^-- --count will decrements the count, then returns the decremented count value
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-1">
<a href="" id="left">
<img src="images/left.png" width="80px" height="80px">
</a>
</div>
<div class="col-xs-6">
<img src="images/1.jpg" id="image">
</div>
<div class="col-xs-1">
<a href="" id="right">
<img src="images/right.png" width="80px" height="80px">
</a>
</div>
</div>

关于Javascript (Jquery), increment/decrement++/-- operator 计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31940465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com