我正在编写一个程序,其中有16个div,每个div都有一个独特的类名,范围从11,12,13 ...... 44.现在我已经编写了一个数学函数来从该数组中随机选择一个数字。我想知道如何用随机选择的类名找到div,然后我需要在这个div中添加一个类。
任何人都可以告诉我为什么添加新课程的随机选择的div不会显示背景图片(images.png)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
.row
{
width:520px;
height:120px;
border-color:#333;
border-width:1px;
}
.sq-color
{
margin: 2px;
width:120px;
height:120px;
float:right;
background-color:#6C0;
}
.mole
{
background-image:url(images.jpg);
}
</style>
<script>
var items = Array(11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44);
var random = items[Math.floor(Math.random()*items.length)]
$('.c'+random).addClass('mole');
</script>
<title>Untitled Document</title>
</head>
<body>
<div class="row">
<div class="sq-color c11"></div>
<div class="sq-color c12"></div>
<div class="sq-color c13"></div>
<div class="sq-color c14"></div>
</div>
<div class="row">
<div class="sq-color c21"></div>
<div class="sq-color c22"></div>
<div class="sq-color c23"></div>
<div class="sq-color c24"></div>
</div>
<div class="row">
<div class="sq-color c31"></div>
<div class="sq-color c32"></div>
<div class="sq-color c33"></div>
<div class="sq-color c34"></div>
</div>
<div class="row">
<div class="sq-color c41"></div>
<div class="sq-color c42"></div>
<div class="sq-color c43"></div>
<div class="sq-color c44"></div>
</div>
</body>
</html>
答案 0 :(得分:0)
使用它:
$(function() {
var items = Array(11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44);
var random = items[Math.floor(Math.random()*items.length)];
$('.c'+random).addClass('mole');
});
文件准备好了。
修改强>
并添加jquery文件:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
检查图片
$(function() {
var i = new Image();
i.src = 'images.jpg';
i.onerror = function(e) {
alert('error on load image');
};
var
items = Array(11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44),
index = Math.floor(Math.random()*items.length),
random = items[index];
$('.c'+random).addClass('mole');
});