0

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

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>

我知道我的代码在这一点上真的很笨重和臃肿,但这是多次错误测试的结果,没有让东西正常工作。

4

1 回答 1

0

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

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

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

但其余的我有点困惑;你能从视觉上解释一下你期望这个东西看起来如何,我们可以给你关于要遵循的模式的基本想法吗?(请记住,堆栈溢出往往不会为您完成全部工作)

(评论后:)所以这听起来像是在 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,您应该只需要一个向上箭头、一个向下箭头和一个图像。如果您愿意,您可能还有一种方法可以在显示之前预先缓存您要向用户显示的每个图像。(不过,您可能至少想尝试自己解决这个问题)

于 2013-05-28T20:31:28.947 回答