我在按下img时尝试使用onclick功能。 我想根据被按下的小img改变一个大的主要img(" mainPants")。 我的代码存在问题 - 每次点击'在小img上将主要img改为最后一个(红色裤子)。
这是我的代码:
<img id="mainPants" src="images/bluePants.png">
<img class="img1" id="pBlack" onclick="changeImage()" src="images/blackPants.png">
<img class="img1" id="pPink" onclick="changeImage()" src="images/pinkPants.png">
<img class="img1" id="pRed" onclick="changeImage()" src="images/redPants.png">
<script>
function changeImage(){
var blackPants = document.getElementById("pBlack");
var pinkPants = document.getElementById("pPink");
var redPants = document.getElementById("pRed");
var newImg = document.getElementById('mainPants');
blackPants.addEventListener('onclick', function(){
newImg.src = "images/blackPantsBig.png";
}());
pinkPants.addEventListener('onclick', function(){
newImg.src = "images/pinkPantsBig.png";
}());
redPants.addEventListener('onclick', function(){
newImg.src = "images/redPantsBig.png";
}());
};
</script>
答案 0 :(得分:1)
您可以在每次点击时运行所有回调:
blackPants.addEventListener('onclick', function(){
newImg.src = "images/blackPantsBig.png";
}()); // these "()" brackets run function right after it is created
您还绑定了所有回调两次 - 第一次使用onclick="changeImage()"
属性的HTML,第二次使用addEventListener
。试试这个:
<script>
function changeImage(e) {
var newImg = document.getElementById('mainPants');
switch (e.target.id) {
case 'pBlack':
newImg.src = "images/blackPantsBig.png";
break;
case 'pPink':
newImg.src = "images/pinkPantsBig.png";
break;
case 'pRed':
default:
newImg.src = "images/pinkPantsBig.png";
}
}
</script>
答案 1 :(得分:0)
<img class="img1" id="pBlack" onclick="changeImage(this)" src="images/blackPants.png">
<img class="img1" id="pPink" onclick="changeImage(this)" src="images/pinkPants.png">
<img class="img1" id="pRed" onclick="changeImage(this)" src="images/redPants.png">
<script>
function changeImage(img) {
var newImg = document.getElementById('mainPants');
switch (img.id) {
case 'pBlack':
newImg.src = "images/blackPantsBig.png";
break;
case 'pPink':
newImg.src = "images/pinkPantsBig.png";
break;
case 'pRed':
default:
newImg.src = "images/redPantsBig.png";
}
}
</script>