jQuery按时间间隔单击各个元素

时间:2014-10-13 14:58:50

标签: javascript jquery

我使用JQVMap在页面上渲染世界地图。我需要按特定顺序每10秒自动单击一个单独的地图区域。这是我到目前为止的javascript:

//get each region in the sequence
var asiaID = document.getElementById('jqvmap1_cn'); //China
var americaID = document.getElementById('jqvmap1_ar'); //Argentina
var africaID = document.getElementById('jqvmap1_et'); //Ethiopia
var europeID = document.getElementById('jqvmap1_ru'); //Russia
var eastID = document.getElementById('jqvmap1_pk'); //Pakistan

var regionArray = [asiaID, americaID, africaID, europeID, eastID];
var arrayLength = regionArray.length;

//trigger sequence on time interval
setInterval(autoCycle, 10000);

//cycle through each region with click
function autoCycle(){
    //loop through each region
    for (var i = 0; i < arrayLength; i++) {
        jQuery(regionArray[i]).trigger('click');
        console.log(regionArray[i]);
    }
}

使用此代码,每10秒钟同时点击regionArray中的所有区域。如果有意义的话,我需要按顺序单独点击它们。 for()循环不适合这个吗?

2 个答案:

答案 0 :(得分:3)

您可以使用此逻辑:

var i = 0;
setInterval(function(){autoCycle(i++%arrayLength)}, 10000);

//cycle through each region with click
function autoCycle(i) {
    jQuery(regionArray[i]).trigger('click');   
}

答案 1 :(得分:1)

1)如果使用jquery,则不需要getElementByID 2)您可以使用setTimeout和recursion

var regionArray = ['#jqvmap1_cn', '#jqvmap1_ar', '#jqvmap1_et', '#jqvmap1_ru', '#jqvmap1_pk'];
    var arrayLength = regionArray.length;

    function autoCycle(i) {
      if (i < arrayLength) {
        jQuery(regionArray[i]).trigger('click');
        setTimeout(function(){autoCycle(++i);}, 10000);
      }
    }

    autoCycle(0);