Javascript onclick事件只工作一次? [英] Javascript onclick event only work once?
问题描述
嘿,
我正在一个网页上显示图片,下面有一列较小的图片可以点击,这样它可以显示为一个大的上面的图片。我能够使用javascript的onclick事件处理程序,但在图像更改后,当我单击另一个图像时,它就停止了更改。谁知道为什么?我猜这是onclick事件的限制。
这是我的代码块:
HTML
Hey,
I'm working on a web page that shows image with a column of smaller images below that can be clicked so it can show as a big picture above. I was able to make it work with onclick event handler for javascript but after the image changes, when I clicked another image it just stopped from changing. Anyone know why? I'm guessing that it's a limitation of onclick event.
Here's my code block:
HTML
<img class="slasher" src="../img/Slash.jpg" height="800" width="1100">
<div class="row">
<img class="slide1ID" src="../img/slide1.jpg" height="300px" width="385px" önclick="changeImage()"/>
<img class="slide2ID" src="../img/slide2.jpg" height="300px" width="385px" önclick="changeImage()"/>
<img class="slide3ID" src="../img/slide3.jpg" height="300px" width="385px" önclick="changeImage()"/>
</div>
Javascript
Javascript
function changeImage(){
if(document.getElementByClassName("slide1ID")){
document.getElementByClassName("slasher").src="../img/slide1.jpg";
}
if(document.getElementByClassName("slide2ID")){
document.getElementByClassName("slasher").src="../img/slide2.jpg";
}
推荐答案
您将以一种特殊的方式进行此操作 - 使用类名来识别点击该项目。使用id更常规。
为图像标记添加一个ID如下:
You're going about this in a peculiar fashion - using the class name to identify the item clicked. It's more conventional to use an id.
add an id to the image tag something like this:
<img ....="" id="space1" onclick="changeImage(id)">
</img>
并将您的功能重新排列为以下内容:
and rearrange your function to something like this:
function changeImage(id) {
switch(id) {
case 'space1': do something
break;
case 'space2': do something
break;
case 'space3': do something
break;
} // end switch(id)
} // end function changeImage(id)
您会发现这更容易管理 - 考虑到一个类可以在多个位置使用(理想情况下,您的CSS将允许您这样做) - 这不是测试单个项目的最佳方式鉴定。另一方面,id是不应该在给定页面上重用。你也可以使用document.getElementById()获得很多功能。
You'll find this easier to manage - consider that a class can be used in more than one location (and ideally, your CSS will allow you to do this) - it's not the best way to test for an individual item to be identified. id's on the other hand, are not supposed to be reused on a given page. You can also have a lot of functionality using document.getElementById()
这篇关于Javascript onclick事件只工作一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!