admin管理员组

文章数量:1310254

I've got a block of HTML that looks like this:

<div id="banners">
    <a href="p1.html"><img src="img1.jpg" /></a>
    <a href="p2.html"><img src="img2.jpg" /></a>
    <a href="p3.html"><img src="img3.jpg" /></a>
    <a href="p4.html"><img src="img4.jpg" /></a>
    <a href="p5.html"><img src="img5.jpg" /></a>
</div>

Using JavaScript, I'd like to randomly pick two of those images and their corresponding links and display them, while hiding the others. Also, they need to not be duplicates, meaning, I want to avoid showing something like img1.jpg img1.jpg at the same time.

jQuery is being used on the site, so it'd be nice if the proposed solution was a jQuery solution.

It's unfortunate that I don't have access to the backend of this site, or else I'd explore a server-side solution. It's just not possible in this instance.

I've got a block of HTML that looks like this:

<div id="banners">
    <a href="p1.html"><img src="img1.jpg" /></a>
    <a href="p2.html"><img src="img2.jpg" /></a>
    <a href="p3.html"><img src="img3.jpg" /></a>
    <a href="p4.html"><img src="img4.jpg" /></a>
    <a href="p5.html"><img src="img5.jpg" /></a>
</div>

Using JavaScript, I'd like to randomly pick two of those images and their corresponding links and display them, while hiding the others. Also, they need to not be duplicates, meaning, I want to avoid showing something like img1.jpg img1.jpg at the same time.

jQuery is being used on the site, so it'd be nice if the proposed solution was a jQuery solution.

It's unfortunate that I don't have access to the backend of this site, or else I'd explore a server-side solution. It's just not possible in this instance.

Share Improve this question asked Aug 9, 2012 at 11:29 ctrlaltdelctrlaltdel 6852 gold badges10 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7
var allBanners = $('#banners a');
allBanners.hide();

var index = Math.floor(Math.random() * allBanners.length);
allBanners.eq(index).show();

var index2 = Math.floor(Math.random() * allBanners.length - 1);
allBanners.not(allBanners.eq(index)).eq(index2).show();

Demo

var elem = $("#banners a");
var img1 = Math.floor(Math.random() * elem.length), 
    img2 = Math.floor(Math.random() * elem.length);

while (img1===img2) {
  img2 = Math.floor(Math.random() * elem.length);
}

elem.hide();
elem.eq(img1).show();
elem.eq(img2).show();

FIDDLE ​

$('a').hide();
var count = 0;
while(count < 2) {
var number = 1 + Math.floor(Math.random() * 5); 
if($('a[href="p' + number + '.html"]:visible').length == 0) {
 $('a[href="p' + number + '.html"]').show();
 count++;
}
}

This ensures the unbiased randomness over choosing those two images.

本文标签: Randomly display two of five images with JavaScript (jQuery)Stack Overflow