按钮上的数组随机循环数组

时间:2014-05-27 09:27:16

标签: jquery html arrays loops

我遇到一个循环问题,我希望数组在小提琴中提供iframe的src。我希望循环在同一个按钮上迭代遍历数组,直到它到达循环结束。

以下是我的代码:

HTML:

<div id="jgbutton" class="demo">
    <button>Push me, Lara</button>
    <p>(and again, till you like what you see)</p>
</div>
<div class="datecontentwrapper">
    <iframe src="" id="iframeFILL"></iframe>
</div>

jQuery的:

jQuery("#jgbutton").click(function () {
var dateplaces = ["http://www.tate.org.uk/whats-on/tate-modern/exhibition/henri-matisse-cut-outs", "http://www.bootstrapcompany.co.uk/22_dalston_roof_park", "http://commons.wikimedia.org/wiki/File:Light_Painting_1_-_Booyeembara_Park.jpg", "http://www.happinessforgets.com/", "http://www.gordonswinebar.com/defaultm.php"];
        var arrayLength = dateplaces.length;
        var genrandomdate = dateplaces[Math.floor(Math.random() * dateplaces.length)];

        for (var i = 0; i < arrayLength; i++) {
            $("#iframeFILL").attr("src", dateplaces[i]);
            $(".datecontentwrapper").show('slow');
            $("p").show();
        }

});

的jsfiddle: http://jsfiddle.net/hslincoln/8Gnuy/9/

我是否可以全局声明变量,而不是在for循环中声明?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

你需要循环什么? 只需将其删除即可完成预期的操作。

而不是每次按钮上的循环调用随机元素点击:

 $("#iframeFILL").attr("src", genrandomdate);
    $(".datecontentwrapper").show('slow');
    $("p").show();

Updated Fiddle

如果您想通过链接循环(非随机),请使用:

    var currentIndex = $("#iframeFILL").data('index');
    if (!currentIndex || currentIndex>arrayLength) {
        fill(1);
    } else {
        fill(currentIndex);
    }

    function fill(i) {            
        $("#iframeFILL").attr("src", dateplaces[i-1]).data('index', i+1);
        $(".datecontentwrapper").show('slow');
        $("p").show();
    }

Another fiddle