我对jQuery不是很熟悉,但我一直在尝试使用此脚本随机化(在页面加载时)a
多个div
个链接中的class="category"
个链接{{1} }。每个a
链接都有一个" fancybox-img"并且在标记中包含img
- 我希望每个img
在随机化后保持在原始a
内
JS BIN:
http://jsbin.com/yupizuqubu/1/edit
HTML:
<div class="category">
<h4>PIZZA CATS</h4>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="https://pbs.twimg.com/profile_images/419613535971184640/FEzxylpk_400x400.jpeg" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/shnozzle.jpg"><img src="http://www.spindletoprollergirls.com/webdesign/KCruse/Images/Cats%20in%20Space/PizzaKittenLG.jpg" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="http://cdn.acidcow.com/pics/20120124/cats_on_pizza_boxes_20.jpg" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="http://i.imgur.com/OuUe8Da.jpg" class="img-responsive" height="50"></a>
</div>
<div class="category">
<h4>BREAD CATS</h4>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="https://pbs.twimg.com/media/Bmlk3bJIMAE1jlR.jpg:large" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/shnozzle.jpg"><img src="http://www.mancertified.com/wp-content/uploads/2012/02/Cats-bread-slices25.jpg" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="http://letssmiletoday.com/uploads/images/9460-bread-cat.jpg" class="img-responsive" height="50"></a>
<a class="fancybox-thumb" rel="gallery-1" href="img/art/painting/bag-man.jpg"><img src="http://i.ytimg.com/vi/g8du14oxTM8/hqdefault.jpg" class="img-responsive" height="50"></a>
</div>
jQuery的:
$(function() {
$('.category').randomize('a');
$.fn.randomize = function(selector){
var $elems = selector ? $(this).find(selector) : $(this).children(),
$parents = $elems.parent();
$parents.each(function(){
$(this).children(selector).sort(function(){
return Math.round(Math.random()) - 0.5;
}).detach().appendTo(this);
});
return this;
};
})(jQuery);
谢谢你的时间!
答案 0 :(得分:0)
错误发生在选择器$('.category').randomize('a');
这是正确的jQuery代码:
$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.4;
}).detach().appendTo(this);
});
return this;
};
$('.category').randomize('a');