[英]Change Javascript array index
我有一个漫画网站,该网站遍历数据库中的所有图像并将它们显示为缩略图。 用户可以单击其中一张图像,在viewComic.php模板上以正常大小查看它。
我想允许用户按向左和向右箭头浏览图像。
因此,我的想法是:
pagination.php通过遍历数据库结果数组来处理图像在正确页面上的显示(通过偏移)。 用户可以单击一个结果(如下)以转到viewcomic.php模板上的特定图像。
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '">
现在在viewcomic.php上,我得到并显示图像
$imgid = $_GET['id']; $imgpath = $_GET['image']; <center><img src=".<?php echo $imgpath ?>" /></center>
用户可以按左右箭头浏览图像...
问题1:JavaScript是否允许您手动设置数组中的索引位置?
由于我希望允许用户获取下一张和最后一张图像,因此我希望它们从当前所在的图像(在pagination.php中单击的图像)开始,而不是从图像数组的开头开始。 我在URL中传递了$ imgid,所以我要设置javascript img数组索引== $ imgid,这将允许用户继续从停下来的位置滚动浏览图像。
问题2:如何保留数组的当前索引 ?
当我想朝某个方向发展时,它可以正常工作。 但是,如果要更改方向,则必须按两次键。 我发现这是因为在按下(imgIndex ++)键后索引会增加。 这意味着,当它开始向相反方向移动时,首先需要递减以将索引返回到当前图像,然后再次按键以最终显示下一张图像。 我不确定如何解决此问题。 使用++ imgIndex也有问题,因为它会跳过图像。
<?php
getImages() {
//DB connection code omitted
$img = array();
while($row = $catResult->fetch_assoc()) {
$img[] = "'../images/all_comics/" . $row['imgname'] . "'";
}
return $img;
?>
var imgArray = [<?php echo implode(',', getImages()) ?>];
$(document).ready(function() {
var img = document.getElementById("theImage");
img.src = imgArray[0];
var imgIndex = 0;
$(document).keydown(function (e)
{
//next image
if (e.which == 39)
{
if (imgIndex == imgArray.length)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex++];
//now the index is ahead by 1, which is bad if you want to press <-- to get the last image because the index is ahead by 1.
}
//last image
if (e.which == 37)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
});
});
有任何想法吗?
非常感激!
更改操作顺序:
if (e.which == 39) {
imgIndex++;
if (imgIndex>imgArray.length) {
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.