jquery:自动更改选择标记列表的选项

时间:2012-09-27 11:39:39

标签: jquery html

我在select标签

中有两个下拉列表项

首先选择标签有年份列表 第二个选择标记有月份列表

<SELECT id="year" onchange="showData();">
  <OPTION VALUE="2012">2012
  <OPTION VALUE="2011">2011
  <OPTION VALUE="2010">2010
  <OPTION VALUE="2009">2009
  <OPTION VALUE="2008">2008
</SELECT>

<SELECT id="month" onchange="showData();">
  <OPTION VALUE="jan">jan
  <OPTION VALUE="feb">feb
  <OPTION VALUE="mar">mar
        .
        .
  <OPTION VALUE="dec">dec
</SELECT>

所以我怎么能在5秒后自动更改月份&amp;一年60秒

什么是我的jquery

function changeMonthYear() {    
    //what to code here to change option of select tag
    //automatically after some time 
    //say 5 sec per month & after 60 sec year will be changed
    showData();    
}

showData() {    
    //some logic will show data for selected year & month    
}

如何解决问题

3 个答案:

答案 0 :(得分:4)

试试吧

function changeYear() {

        $('option:selected', '#year').removeAttr('selected').next('option').attr(
                'selected', 'selected'); //your id of select tag is 'year'

        showData();

    }

    function changeYearMonth() {

        $('option:selected', '#month').removeAttr('selected').next('option')
                .attr('selected', 'selected'); //your id of select tag is 'month'

        showData();

    }

    setInterval(changeYear, 60000);
    setInterval(changeYearMonth, 5000);

    showData(){

    //some logic will show data for selected year & month

    }

答案 1 :(得分:1)

这是一个简单的解决方案,一旦完成所有选项,它将从头开始再次继续:

var i=0;
function changeYear() {
  var count = $('#year option').length;
  i = (i == count) ? 0 : i;
  $('#year').val($('#year option').eq(i++).val());
}

setInterval(changeYear, 1000); // example is 1 second!

Here's a fiddle

你也必须做同样的事情来改变这个月,只是以为我会把它留在这里,因为它比其他例子更清洁(在我看来)

答案 2 :(得分:0)

var i=0,j=0;

 function changeMonthYear() {

        //what to code here to change option of select tag
        //automatically after some time 
        //say 5 sec per month & after 60 sec year will be changed
        setInterval(showData('year'),1000*60);
        setInterval(showData('month'),1000*5);

    }
function showData(that)
{
if(that=='year')
{    
document.getElementById(that).getElementsByTagName('option')[i].selected=true;
    i++;
}
else
{
document.getElementById(that).getElementsByTagName('option')[j].selected=true;
j++;
}
}
changeMonthYear();