Created
October 26, 2011 07:24
-
-
Save hara-y-u/1315679 to your computer and use it in GitHub Desktop.
ランダムな要素をフィルタするjQueryメソッド(プラグイン)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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