javascript(jquery)数组中的前五个如何onclick

时间:2014-06-24 09:28:59

标签: javascript jquery arrays

嗨我有一个图像数组,使用jquery shuffle函数点击一个随机播放按钮,我还想做的是添加一个按钮,只显示点击后的前五个图像。

所以问题是当单击按钮时,如何从数组中拉出前5个图像?

代码如下:

HTML:

<div id="array" class="thirdcanvas"></div>
<button class="array">Shuffle</button>

JS:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
jQuery(function ($) {

var arr = new Array("images/c1.png", "images/c2.png", "images/c3.png", "images/c4.png", "images/c5.png", "images/c6.png", "images/c7.png", "images/c8.png", "images/c9.png", "images/c10.png", "images/cj.png", "images/ck.png", "images/cq.png", "images/d1.png", "images/d2.png", "images/d3.png", "images/d4.png", "images/d5.png", "images/d6.png", "images/d7.png", "images/d8.png", "images/d9.png", "images/d10.png", "images/dj.png", "images/dk.png", "images/dq.png", "images/h1.png", "images/h2.png", "images/h3.png", "images/h4.png", "images/h5.png", "images/h6.png", "images/h7.png", "images/h8.png", "images/h9.png", "images/h10.png", "images/hj.png", "images/hk.png", "images/hq.png", "images/s1.png", "images/s2.png", "images/s3.png", "images/s4.png", "images/s5.png", "images/s6.png", "images/s7.png", "images/s8.png", "images/s9.png", "images/s10.png", "images/sj.png", "images/sk.png", "images/sq.png")

  $.each($.shuffle(arr), function (_, src) {
    $('<img />', {
        src: src
    }).appendTo('#array')
})
$('button.array').click(function () {
    $('#array').shuffle()
});
});

(function ($) {

$.fn.shuffle = function () {
    var _self = this,
        children = $.shuffle(this.children().get());
    $.each(children, function () {
        _self.append(this)
    })
    return this;
};

$.shuffle = function (arr) {
    for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
};

$( array ).slice( 0, 5 );

})(jQuery);
</script>

1 个答案:

答案 0 :(得分:0)

我重写了你的代码,因为它返回了太多错误。我相信我已经实现了你想要的功能。

我使用shuffle()函数随机化数组。这不是标准的jQuery函数more info on that in this question.

我使用slice函数返回混洗数组的前5个命中。 More info on slice.

然后,我使用了混洗拆分数组的每个函数将图像附加到目标容器。

$('button.array').on('click', function(){
    shuffle(arr);
    var firstFive = arr.slice(0, 5);   
    $('#array').empty();
    $.each(firstFive, function(i,v){
        console.log(v);
        $('#array').append('<img src="'+v+'">');
    });
});

工作示例: http://jsfiddle.net/RD6Gu/3/