在超过1个div中使用相同类型的javascript

时间:2014-02-25 06:52:35

标签: javascript html css

我正在使用javascript创建立方体动画,但是当我使用相同的div javascript创建另一个id时,第二个div不使用dat相同的脚本。我怎么做?所以我可以在多个divs中使用相同的脚本?

代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Image Cube</title>
<style type="text/css">
#basicCube { width: 150px; height: 150px;}
#basicCube img{border:3px solid #ccc}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.imagecube.js"></script>
<script type="text/javascript">
$(function () {
    $('#basicCube').imagecube();
});
</script>
</head>
<body>
<div id="basicCube">
    <img src="1.jpg" alt="Gorge" title="Gorge">
    <img src="2.jpg" alt="Gorge" title="Gorge">
    <img src="3.jpg" alt="Gorge" title="Gorge">
    <img src="4.jpg" alt="Gorge" title="Gorge">
    <img src="5.jpg" alt="Gorge" title="Gorge">
    <img src="6.jpg" alt="Gorge" title="Gorge">
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

$(function () {
    $('.basicCube').imagecube();
});
</script>
</head>
<body>
<div class="basicCube">
    <img src="1.jpg" alt="Gorge" title="Gorge">
    <img src="2.jpg" alt="Gorge" title="Gorge">
    <img src="3.jpg" alt="Gorge" title="Gorge">
    <img src="4.jpg" alt="Gorge" title="Gorge">
    <img src="5.jpg" alt="Gorge" title="Gorge">
    <img src="6.jpg" alt="Gorge" title="Gorge">
</div>
</body>
</html>

答案 1 :(得分:2)

您不应在文档中多次使用标识符。在这种情况下,您将需要使用类:

CSS

.basicCube { width: 150px; height: 150px;}
.basicCube img{border:3px solid #ccc}

HTML

<div class="basicCube">
    <img src="1.jpg" alt="Gorge" title="Gorge">
    <img src="2.jpg" alt="Gorge" title="Gorge">
    <img src="3.jpg" alt="Gorge" title="Gorge">
    <img src="4.jpg" alt="Gorge" title="Gorge">
    <img src="5.jpg" alt="Gorge" title="Gorge">
    <img src="6.jpg" alt="Gorge" title="Gorge">
</div>
<div class="basicCube">
    <img src="1.jpg" alt="Gorge" title="Gorge">
    <img src="2.jpg" alt="Gorge" title="Gorge">
    <img src="3.jpg" alt="Gorge" title="Gorge">
    <img src="4.jpg" alt="Gorge" title="Gorge">
    <img src="5.jpg" alt="Gorge" title="Gorge">
    <img src="6.jpg" alt="Gorge" title="Gorge">
</div>

的JavaScript

$(function () {
    $('.basicCube').imagecube();
});

答案 2 :(得分:2)

您只能使用id一次。在那里使用课程。

 <div class="basicCube">
    <img src="1.jpg" alt="Gorge" title="Gorge">
    <img src="2.jpg" alt="Gorge" title="Gorge">
    <img src="3.jpg" alt="Gorge" title="Gorge">
    <img src="4.jpg" alt="Gorge" title="Gorge">
    <img src="5.jpg" alt="Gorge" title="Gorge">
    <img src="6.jpg" alt="Gorge" title="Gorge">
</div>

$(function () {
    $('.basicCube').imagecube();
});