簡體   English   中英

通過jQuery對隨機字段項進行排序

[英]Sort random field items via jQuery

我有一個HTML幻燈片菜單。 具有以下內容:

<div class="slide">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/1.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/2.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/3.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/4.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/5.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/6.png" alt="">
</div>

而且我想在每次刷新時獲取具有隨機排序的圖像。 我使用以下代碼:

function reorder() {
    var grp = $(".slide").children();
    var cnt = grp.length;

    var temp, x;
    for (var i = 0; i < cnt; i++) {
        temp = grp[i];
        x = Math.floor(Math.random() * cnt);
        grp[i] = grp[x];
        grp[x] = temp;
    }
    $(grp).remove();
    $(".slide").append($(grp));
}

function orderPosts() {
    $(".slide").html(orig);
}​

但是不行。 我可能做錯了什么?

有一種更簡單的方法可以做到這一點。 由於jQuery集合類似於Array,因此您可以在其上調用本機Array原型。 因此,使用本機Array.sort ,您的代碼將被這樣重寫:

var grp = $(".slide").children(); // the original collection, if you want to save it...

Array.prototype.sort.call(grp, function() {
    return Math.round(Math.random())-0.5;
});

$('.slide').empty().append(grp);

這是一個演示: http : //jsfiddle.net/JTGfC/

我不確定這是否100%符合猶太標准,但您可以在此處應用Fisher-Yates,而無需依賴jQuery。

fisherYates(document.getElementsByClassName('slide')[0]);

// Fisher-Yates, modified to shuffle DOM container's children instead of an array.
function fisherYates (node)
{
  var children = node.children,
  n = children.length;

  if (!n) {
    return false;
  }

  while (--n) {
     var i = Math.floor( Math.random() * ( n + 1 ) ),
     c1 = children[n];

     node.insertBefore(c1, children[i]);
   }
}

演示版

您的reorder()函數很好,我在此小提琴中對其進行了測試: http : //jsfiddle.net/kokoklems/YpjwE/

我沒有使用第二個函數orderPosts() ...

這應該為您做:

function reorder() {
    var grp = $(".slide").children();
    var cnt = grp.length;

    var indexes = [];
    // Build a array from 0 to cnt-1 
    for (var i = 0; i < cnt; i++) {
        indexes.push(i);
    } 
    // Shuffle this array. This random array of indexes will determine in what order we add the images.
    indexes = shuffle(indexes);

    // Add the images. (No need to remove them first, .append just moves them)
    for (var i = 0; i < cnt; i++) {
        $(".slide").append($(grp[indexes[i]]));
    }
}

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

隨機播放功能源

工作樣本 (我使用跨度而不是圖像,以更好地顯示結果)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM