我正在编写一个程序,其中有 16 个 div,每个 div 都有一个唯一的类名,范围从 11、12、13... 44。现在我编写了一个数学函数来从该数组中随机选择一个数字。我想知道如何找到具有随机选择的类名的 div,然后我需要向这个 div 添加一个类。
下面的代码,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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)]
</script>
<title>Untitled Document</title>
</head>
<body>
<div class="row">
<div class="sq-color 11"></div>
<div class="sq-color 12"></div>
<div class="sq-color 13"></div>
<div class="sq-color 14"></div>
</div>
<div class="row">
<div class="sq-color 21"></div>
<div class="sq-color 22"></div>
<div class="sq-color 23"></div>
<div class="sq-color 24"></div>
</div>
<div class="row">
<div class="sq-color 31"></div>
<div class="sq-color 32"></div>
<div class="sq-color 33"></div>
<div class="sq-color 34"></div>
</div>
<div class="row">
<div class="sq-color 41"></div>
<div class="sq-color 42"></div>
<div class="sq-color 43"></div>
<div class="sq-color 44"></div>
</div>
</body>
</html>
感谢大家。我尝试了代码并相应地插入,但没有任何变化。似乎没有 DIV 显示 .mole 类中给出的背景图像。
下面是代码。请让我知道我在哪里恭维。我更正了命名约定并将字母“c”添加到类名中。我使用类只是为了有更多的灵活性。
<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>