2010-02-27 53 views

回答

4

保持簡單。這檢索所有的列表項下該列表:

var items = $("#sliding_panels li"); 

然後用Math.random()挑選其中之一。 注意:構造Math.floor(Math.random() * 10))將返回一個介於0和9之間的整數。

var item = Math.floor(Math.random() * items.length); 

可以使用一個jQuery對象上的數組索引運算符來檢索這些元件中的一個。 注意:如果set是jQuery對象,則set[n]相當於set.get(n)

然後,您需要來包裝的jQuery元素,並使用addClass()

$(items[item]).addClass("active"); 
1

請參閱this question瞭解如何獲取隨機元素。

$("#sliding_panels li").get().sort(function(){ 
    return Math.round(Math.random())-0.5 
}).slice(0,1).addClass("active"); 

感謝duckyflip了原來的答案。

另一種方法是在同一問題中提到的:random plugin

實施例:

$("#sliding_panels li:random").addClass("active"); 
+1

我不明白這一點。爲什麼要選擇一個隨機元素?有點奇怪。 – cletus 2010-02-27 02:09:24

+0

似乎有點矯枉過正.. – 2010-02-27 02:24:11

1
var elements = $('ul#mylist li'); 
$ (elements.get (
    Math.round (elements.length*Math.random()-0.5) 
)).addClass ('active'); 
相關問題