【问题标题】:Loop through array on button click with math random使用数学随机在按钮单击时循环遍历数组
【发布时间】:2014-05-27 09:27:15
【问题描述】:

我遇到了一个循环问题,我希望数组在小提琴中提供 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 循环中声明变量吗?

任何帮助将不胜感激!

【问题讨论】:

标签: jquery html arrays loops


【解决方案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

【讨论】:

  • 不完全是因为如果它是随机的,它可以复制一个数组条目。
  • 查看更新的答案。你可以使用随机链接或下一个,但你不能同时使用:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
相关资源
最近更新 更多