用javascript显示随机div [英] Showing random div with javascript
问题描述
正确答案使用以下代码: http://jsfiddle.net/nick_craver/RJMhT/
所以我想要做到上述,但对于我的生活,我不知道该怎么做。
我认为这很简单,就像
< HTML>
< head>
< script type =text / javascript>
var divs = $(div.Image)。get()。sort(function(){
return Math.round(Math.random()) - 0.5; //随机,所以我们得到(0,4)
$(divs).appendTo(divs [0] .parentNode).show();
< /脚本>
< style type =text / css>
div.Image {
display:none;
}
< / style>
< / 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>
但显然不是,因为没有任何东西显示在我的屏幕上。有人能帮助我吗?对于那些对JavaScript没有多少了解的人来说,真的很容易。
感谢你!
在解析页面主体的HTML代码之前,您正在运行脚本,因此元素尚不存在。
将您的代码放在页面的准备好的
事件中:
$(document).ready(function(){
//你的Javascript代码在这里
});
您还错过了包含jQuery库的内容,正如Conner展示的那样。
So I want to show random divs, and I found this stackoverflow solution here: Showing random divs using Jquery
And the correct answer uses this code: http://jsfiddle.net/nick_craver/RJMhT/
So I want to do the above, but for the life of me, I don't know how.
I thought it would be as simple as
<html>
<head>
<script type="text/javascript">
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).appendTo(divs[0].parentNode).show();
</script>
<style type="text/css">
div.Image {
display: none;
}
</style>
</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>
But apparently not, as nothing shows up on my screen. Can somebody help me? Should be really really easy for someone who knows the least bit about javascript I think.
Thank ya!
You are running the script before the HTML code for the body of the page has been parsed, so the elements doesn't exist yet.
Put your code in the ready
event of the page:
$(document).ready(function(){
// your Javascript code goes here
});
Also you are missing the include of the jQuery library, as Conner showed.
这篇关于用javascript显示随机div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!