First off, I am just starting to learn javascript so your patience is appreciated. I have a problem that I am trying to figure out. I am looking for a way to be able to click an image, and then click the image I want to swap it with. To elaborate, I have 9 images labeled 0-9, and 9 blank images. My goal is to be able to click a numbered image and swap it for one of the blank images. All I have come up with is this, but it absolutely does not work in the way I need.
function swap1() {
element = document.getElementById('0')
if (element.src.match("0.jpg")) {
element.src = "blank.jpg";
alert(this.id)
} else {
element.src = "0.jpg";
}
}
id
can't start with a number. Change it to a valid id
like image
or just get the reference to the element via event.target
.
<img id="img0" src="0.jpg" onclick="swap(this);">
<img id="img1" src="1.jpg" onclick="swap(this);">
<img id="img2" src="2.jpg" onclick="swap(this);">
<script>
function swap(d){
if (!d.osrc) d.osrc=d.src; //save the original src file
if (d.blanked){
d.src=d.osrc;
d.blanked=null;
} else {
d.blanked=true;
d.src='blank.jpg';
}
//un-blank the "other guys"
for (var i=0;i<3;i++){ //change the upper bound as you add more images
var obj=document.getElementById('img'+i);
if (obj==d) continue; //skip self
obj.blanked=null;
obj.src=obj.osrc;
}
}
</script>
The above code demonstrates two important techniques: a. passing in self-reference to avoid tedious naming; b. storing state variables in the DOM object
Try this. Say your html like
<img id="myimage" onclick="swap1()" src="0.jpg">
function swap1() {
element = document.getElementById('myimage');
if (element.src.match("0.jpg")) {
element.src = "blank.jpg";
} else {
element.src = "0.jpg";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.