Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
Created October 26, 2011 07:24
Show Gist options
  • Save hara-y-u/1315679 to your computer and use it in GitHub Desktop.
Save hara-y-u/1315679 to your computer and use it in GitHub Desktop.
ランダムな要素をフィルタするjQueryメソッド(プラグイン)
(function($){
$.fn.random = function(n) {
var elms = Array.prototype.slice.call(this), option = {
number: 1
}, ret = [];
$.extend(option, { number: n});
n = option.number;
function randomArrayIterator(array) {
var arr = array.concat(), len = arr.length;
return {
hasNext: function(){
return len ? true : false;
},
next: function(){
if(!len) { return null; }
var i = Math.floor(Math.random() * len--);
return arr.splice(i,1)[0];
}
};
}
var itr = randomArrayIterator(elms);
while(n && itr.hasNext()) {
ret.push(itr.next());
n--;
}
return $(ret);
};
}(jQuery));
// .someClassName な要素の中からランダムな3個に randomlyChosen クラスを付与する
$(function() { $('.someClassName').random(3).addClass('randomlyChosen'); }); //デフォルトは $({}).random(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment