<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<title>Javascript Create Div Element Dynamically</title>
<style type="text/css">
.ex
{
width:200px;
position: relative;
background-color :#CCC;
height:150px;
padding:10px;
margin:5px;
left-margin:0px;
float :left;
}
#newdiv
{
width:800px;
height:800px;
border:1px solid #000;
}
.myimage
{
height: 80;
width: 80;
top:100;
margin:5px;
}
.border
{
border:1px solid #000;
}
</style>
<script>
cc = 1;
function changeimage()
{
if (cc == 0)
{
cc = 1;
$('.myimage').attr('src', 'images/plus.png');
}
else if (cc == 1)
{
cc = 2;
$('.myimage').attr('src', 'images/plus2.png');
}
else if (cc == 2)
{
cc = 3;
$('.myimage').attr('src', 'images/plus2.png');
}
else
{
cc = 0;
$('.myimage').attr('src', 'images/plus2.png');
}
}
</script>
<script type="text/javascript" language="javascript">
var i = 0;
function createDiv()
{
if (i < 6) {
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.setAttribute("align", "left");
divTag.style.margin = "0px auto";
divTag.className = "ex";
divTag.innerHTML = "<img class='myimage' onclick='changeimage()' border='0' src='images/white_contact.png' width='100' height='180' />";
document.getElementById("newdiv").appendChild(divTag)
}
i++;
$(".ex").draggable({containment: 'parent', cursor: 'pointer', opacity: 0.6});
$(".ex").droppable({hoverClass: 'border'});
}
</script>
</head>
<body>
<p align="left">
<b>Click this button to create div element dynamically:</b>
<input id="btn1" type="button" value="create div" onClick="createDiv();" />
<div id = "newdiv">
</div>
</p>
</body>
</html>
添加6 DIV后,我点击一个DIV,所有图像都会改变,现在我想单独更改每个div的图像,我的时间已经不多了。有人可以告诉我哪个部分出了问题,让我解决问题,谢谢
答案 0 :(得分:0)
您需要修改代码,以便只需单击img元素就可以更改其源图像,而不是“myimage”类中的所有img元素。我建议将img元素作为参数传递给changeimage:
divTag.innerHTML = "<img class='myimage' onclick='changeimage(this)' border='0' src='images/white_contact.png' width='100' height='180' />";
这样您就可以只选择点击的图片:
function changeimage(image)
{
if (cc==0)
{
cc=1;
$(image).attr('src', 'images/plus.png');
}
// etc
确保您的点击次数是按照每个img而非全局完成的,需要做更多的工作。这样做的一种方法是将计数放在img元素本身上,例如在image.cc
内cc
而不仅仅是changeimage
(尽管你需要对image.cc
未定义的情况有点小心)。