jquery逐步浏览图像

时间:2013-05-28 20:19:25

标签: javascript jquery

我想做的就是能够使用向上和向下箭头逐步完成顺序命名的图像。我错过了一些简单的东西,我可以使用一些帮助。上下字段不起作用。任何帮助表示赞赏。这是我的代码:

HTML:

<div id = "up" class= "5" idnum= "number5">up up up</div>
<img src="img/n5.png" id = "number5">
<div id = "down" lass= "5" idnum= "number5">down down down</div>

<div id = "up" class= "26" idnum= "number4">up up up</div>
<img src="img/n26.png" id = "number4">
<div id = "down" lass= "26" idnum= "number4">down down down</div>

<div id = "up" class= "28" idnum= "number3">up up up</div>
<img src="img/n28.png" id = "number3">
<div id = "down" lass= "28" idnum= "number3">down down down</div>

<div id = "up" class= "30" idnum= "number2">up up up</div>
<img src="img/n30.png" id = "number2">
<div id = "down" lass= "30" idnum= "number2">down down down</div>

<div id = "up" class= "35" idnum= "number1">up up up</div>
<img src="img/n35.png" id = "number1">
<div id = "down" lass= "35" idnum= "number1">down down down</div>

JavaScript的:

    <script type="text/javascript">
        $(document).ready(function() {
            $("#up").click(function () {
                var ball = $(this).attr("class");
                var idnum = $(this).attr("idnum");
                var test = $(this).find("img").attr("id");
                ball++;
                console.log("ball = "+ball);
                console.log("idnum = "+idnum);
                console.log("test = "+test);
                $("#"+idnum).attr("src","img/n"+ball+".png");

            });


            $("#down").click(function () {
                var ball = $(this).attr("class");
                var idnum = $(this).attr("idnum");
                var test = $(this).find("img").attr("id");
                ball--;
                console.log("ball = "+ball);
                console.log("idnum = "+idnum);
                console.log("test = "+test);
                $("#"+idnum).attr("src","img/n"+ball+".png");

            });
        });
    </script>

我知道我的代码在这一点上非常笨拙和臃肿,但这是多次错误测试的结果,并没有让工作得到满足。

1 个答案:

答案 0 :(得分:0)

加布是正确的;您不能多次使用某个ID。我的建议是这样定位:

<div id="pictureNavigator">
  <div class="upButton optionalOtherClass">up</div>
  <img src="n5.png"/>
  <div class="downButton">down</div>

<!-- ...etc...-->
</div>

但其余部分我有点困惑;你能直观地解释一下你对这个东西的看法吗?我们可以给你关于这个模式的基本想法吗? (请记住,Stack Overflow往往不会为你完成整个工作)

(评论后:)所以这听起来像Javascript方面控制起来非常简单,而不是每个实例都有HTML。基本思想是将图像索引(和上/下边界)保持为Javascript变量,并在每次单击时将图像的src属性替换为正确的属性。我会给出一些未完成的代码来展示我在想什么。

$(function() {
    var imgIndex = 10;
    var minIndex = 0;
    var maxIndex = 55;

    function refreshIndex() {
        // here, set the image's src to "n13.png", or whatever imgIndex is.
    }

    $('#pictureNavigator .upButton').click(function() {
        imgIndex++;
        refreshIndex();
    });
    $('#pictureNavigator .downButton').click(function() {
        imgIndex--;
        refreshIndex();
    });
});

可能还有其他一些事情要考虑,但我认为这应该足够了。对于HTML,您只需要一个向上箭头,一个向下箭头和一个图像。如果您愿意,可能还有一种方法可以在显示之前预先缓存您要向用户显示的每个图像。 (你可能想要至少尝试自己计算一个)