0

我的计数器在 10 次之后变为 0。记住我需要它到 1 而不是 11 或 0!我每次都需要一个新的jpg,例如test.1.jpg、test.2.jpg、test.3.jpg等等。

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <script>
            $(document).ready(function() {

                var timer, counter = 1,
                    changepic = function(pic) {

                        var src = pic.attr("src");

                        counter = counter + 1;

                        if (counter == 11) { // <- i tested my if clauses but not working any ideas?maybe we can solve it with easy if clauses
                            counter = 1;
                        }

                        pic.attr("src", src.substring(0, src.lastIndexOf('.') - 1) + counter + ".jpg");

                    };

                $('img').hover(function() {

                    var $this = $(this);

                    timer = setInterval(function() {
                        changepic($this);
                    }, 1000);

                }, function() {
                    clearInterval(timer);
                });

            });
        </script>
    </head>
    <body>
        <table style="float:left;">
            <tr>
            <tr>
                <td><img src="pics/test.1.jpg" /><br />Text</td>
            </tr>
            </tr>
        </table>
    </body>
</html>
4

1 回答 1

1

当 counter 等于 11 时,问题就来了;

src.substring(0, src.lastIndexOf('.') - 1) + counter + ".jpg"; 
//test.1 + 1 + .jpg ---> test.11.jpg

尝试

src.replace(/\d{1,2}\.jpg$/, counter + ".jpg");
于 2012-12-10T00:38:11.863 回答