0
下面的代码运行得尽可能警报(“点击左边的额外图像”),然后它没有做任何事情,点击额外的图像被添加到左div 。当点击额外的图像(id =“extraImage”)时,我希望JS将“extraImage”元素的颜色更改为红色。此外,我需要更改执行代码的顺序并运行警报(“点击左侧的额外图像”)添加图片后。任何想法不胜感激。JavaScript - onclick事件没有运行,代码序列不正确
<html>
<head> </head>
<body>
<div id="containerLeft">
</div>
<div id="containerRight">
</div>
<script>
var i = 1
var pocetSmilikov = prompt("enter number of smiley faces");
alert("i will add" + pocetSmilikov);
while (i <= pocetSmilikov)
{
insert();
i++;
}
insertExtraToLeft();
function insert() {
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAdded.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
var the_node = document.getElementById("containerRight").lastChild;
var the_clone = the_node.cloneNode(true);
document.getElementById("containerLeft").appendChild(the_clone);
}
function insertExtraToLeft() {
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id = "extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}
alert("click on extra image on the left");
extraImage.onclick = extraImgFound();
function extraImgFound() {
document.getElementById("extraImage").style.color = "red";
}
</script>
</body>
</html>
'extraImage.onclick = extraImgFound;'不调用函数(用'()'),除非函数本身返回到绑定到该处理程序的功能。 –
我删除了括号并重新运行,但仍然没有任何反应,当我点击已被代码添加的额外图像时... – whada
extraImage未定义? – bestprogrammerintheworld