使用Href更改图像的src

时间:2013-03-19 17:00:38

标签: javascript jquery

我想每隔5秒从链接标记中用“href”更改标记的src。

这是代码:

<div id="bgStretch"><img id="bgStretchimg" src="images/picture1.jpg" alt=""></div> <!--   here is the image src i want to change-->

<nav class="bgNav">
 <ul>
  <li class="active"><a href="images/picture1.jpg"></a></li>
  <li><a href="images/picture2.jpg"></a></li>
 </ul>
</nav>
<!--these are the links so i hope you guys to gimme a solution in javascript-->

这是我试过的jquery:

<script>
  $(document).ready(function() {
    var items = $("nav.bgNav ul li");
    var index = -1;

    function next() {
        // if not the very first iteration, 
        // remove the active class from prev item
        if (index !== -1) {
            var urlI=$(this).("a").attr(href);
            items.eq(index).removeClass("active");
        }
        // go to next item
        ++index;
        // if past end, wrap to beginning
        if (index >= items.length) {
            index = 0;
        }
        // add active class to next item
        items.eq(index).addClass("active");
    $('#bgStretchimg').attr('src', urlI);
        // schedule next iteration
        setTimeout(next, 1000);
    }

    next();
});

</script>

它不与我合作,所以我问你们,谢谢你们。

1 个答案:

答案 0 :(得分:1)

很抱歉,如果花了很长时间!

这是一个working JsFiddle

$(document).ready(function () {

     var items = $("nav.bgNav ul");
     var img = $("#bgStretchimg");

     next();

     function next() {

         var urlI = items.children('.active').children("a").attr('href');

         var nextI = items.children('li.active').removeClass("active").next();
         if (nextI.length == 0) {
             nextI = items.children().eq(0);
         }

         nextI.addClass('active');
         img.attr('src', urlI);

         // schedule next iteration
         setTimeout(function () {
             next();
         }, 2000);
     }
 });

如果你想在第一次调用之前有一个延迟,你可能想把它放在setTimeout中,就像它在函数中一样,所以它在第一次调用之前等待。

// in document ready directly
setTimeout(function () {
    next();
}, 2000);    

也可能想要找到一个已经像这样构建的插件:jQuery Cycle