2013-03-04 35 views
3

我正在为获得什么似乎是一个合理简单的脚本功能而努力,我希望在浏览器刷新时随机使用七个Div。使用jQuery随机加载div

的HTML显示为这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 

<title>Strict</title> 

<link rel="stylesheet" type="text/css" href="style.css"> 

<script type="text/javascript" src="jquery-1.9.1.min.js"></script> 

<script> 
    var divs = $("div.Image").get().sort(function(){ 
    return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
    }).slice(0,4) 
    $(divs).show(); 
</script> 

</head> 

<body> 


<div class="Image"><img src="image1.jpg">1</div> 
<div class="Image"><img src="image2.jpg">2</div> 
<div class="Image"><img src="image3.jpg">3</div> 
<div class="Image"><img src="image4.jpg">4</div> 
<div class="Image"><img src="image5.jpg">5</div> 
<div class="Image"><img src="image6.jpg">6</div> 
<div class="Image"><img src="image7.jpg">7</div> 

</body> 
</html> 

在那里的jQuery脚本应该是:

var divs = $("div.Image").get().sort(function(){ 
return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
}).slice(0,4) 
$(divs).show(); 

CSS限制为:

div.Image { 
display: none; 
} 

没有加载在所有的,目前。

我还是这个品牌的新手,所以如果这是最基本的,我将不得不原谅自己。

回答

3

请将您的代码包装在document.ready内。

$(document).ready(function(){ 
    var divs = $("div.Image").get().sort(function() 
    { 
     return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
    }).slice(0,4); 

    $(divs).show(); 
}); 
2

将函数环绕在$(document).ready的周围,以便在页面完全加载后加载。执行脚本时,页面上尚未加载div元素。

$(document).ready(function(){ 
    var divs = $("div.Image").get().sort(function(){ 
    return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
    }).slice(0,4) 
    $(divs).show(); 
}); 

工作实例:http://jsfiddle.net/FyzXF/

2

试试这个,

$(function(){ 
    var divs = $("div.Image").get().sort(function(){ 
       return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
       }).slice(0,4) 
    $(divs).show(); 
}); 
1

首先,你来包装你的js代码为$(function(){ ... })块:

$(function(){ 

    var divs = $("div.Image").get().sort(function(){ 
    return Math.round(Math.random())-0.5; //random so we get the right +/- combo 
    }).slice(0,4) 
    $(divs).show(); 

}); 

这意味着您的代码在执行时执行DOM已满载。

+0

伟大的东西人,谢谢你的所有信息!我相信这是在图像之前加载的脚本。 – spl 2013-03-04 11:24:58

1

非常简单。试试这个

$(function(){ 
    var ind = Math.floor((Math.random()*7)+1); 
    $("div.Image:eq("+ind+")").show(); 
});