2016-11-28 77 views
0

我已經完成了上一個和下一個的下拉菜單。 我想知道如何每n秒自動更改下拉選項值。 https://jsfiddle.net/wmwayysz/如何自動檢測每30秒的下拉選項

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">  
</script> 
<button type="button" id="prev">Previous</button> 
<select id="selectBox" onchange="currentSlide(value);" class="selectpicker"> 
<option value="1" class="options">Electronics</option> 
<option value="2" class="options">Clothing</option> 
<option value="3" class="options">Health</option> 
    <option value="4" class="options">Food</option> 
<option value="5" class="options">Travel</option> 
<option value="6" class="options">Mobiles</option> 
<option value="7" class="options">Grocery</option> 
<option value="8" class="options">Recharge</option> 
<option value="9" class="options">Furniture</option> 


接下來

$.fn.loopNext = function(selector) { 
    var selector = selector || ''; 
    return this.next(selector).length ? this.next(selector) :  
    this.siblings(selector).addBack(selector).first(); 
    } 
    $.fn.loopPrev = function(selector) { 
    var selector = selector || ''; 
    return this.prev(selector).length ? this.prev(selector) :  
     this.siblings(selector).addBack(selector).last(); 
    } 
    $("#next").click(function() { 
    $('#selectBox > option:selected') 
     .removeAttr('selected') 
     .loopNext('option') 
      .prop('selected', 'selected'); 
    }); 

    $("#prev").click(function() { 
    $('#selectBox > option:selected') 
    .removeAttr('selected') 
     .loopPrev('option') 
     .prop('selected', 'selected'); 
    }); 

    function currentSlide(selectionValue) { 
     console.log(selectionValue); 
    } 

回答

0

你要調用的代碼相同的迭代,你正在使用接下來的一段時間間隔後。所以通用代碼進入功能。 這是它的小提琴。 https://jsfiddle.net/wmwayysz/2/

這裏是你的JavaScript代碼更新

$.fn.loopNext = function(selector) { 
    var selector = selector || ''; 
    return this.next(selector).length ? this.next(selector) : this.siblings(selector).addBack(selector).first(); 
} 
$.fn.loopPrev = function(selector) { 
    var selector = selector || ''; 
    return this.prev(selector).length ? this.prev(selector) : this.siblings(selector).addBack(selector).last(); 
} 
$("#next").click(funShowNext); 
setInterval(funShowNext,3000); 

function funShowNext() { 
    $('#selectBox > option:selected') 
    .removeAttr('selected') 
    .loopNext('option') 
     .prop('selected', 'selected'); 
} 

$("#prev").click(function() { 
    $('#selectBox > option:selected') 
    .removeAttr('selected') 
    .loopPrev('option') 
     .prop('selected', 'selected'); 
}); 

function currentSlide(selectionValue) { 
    console.log(selectionValue); 
} 
+0

其工作只有一次從電子產品到服裝 –

1

試試這個

setInterval(function() { 
    $('#next').trigger('click'); 
}, 30000)