2013-03-19 3 views
-7

Я хотел бы изменить src тега с помощью «href» из тега ссылки каждые 5 секунд.Изменение src изображения с помощью Href

Это код:

<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> 

это не работает со мной, так что я спросил вас, ребята, и спасибо.

+11

Что вы пробовали? Мы можем помочь вам исправить существующий код, но я не буду предлагать полное решение ... –

+1

ditto, dont be lazy – box86rowh

+0

Хорошо, я отредактировал documet, так что надеюсь, что вы мне поможете и много. –

ответ

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

+0

отличный брат отличный :) –

+0

@JefferyKilluminati Надеюсь, это поможет! Вы были близки. Основной проблемой был первый селектор '$ (this)' –

+0

ах, да, я был обеспокоен этим, но большое вам спасибо –

Смежные вопросы