简体   繁体   中英

Javascript Swap Images on Button Click

I currently have 4 buttons that should swap from one image to another once clicked. I can get the first two to work, but once I click the third and fourth, once I click another button the images don't disappear - they stay on the screen.

I have the current code in the document head:

 function showImg(strShow, strHide) { document.getElementById(strShow).style.display = 'block'; document.getElementById(strHide).style.display = 'none'; } 
 <div id="image1"> <INPUT type="submit" class="myButton1" value="" button onclick="showImg( 'a', 'b', 'c', 'd' )"></button> <img id="a" src="Website Photos/scannedimages/remembranceivy.jpg" width="220" height="116.895" style="display:none" alt="A" /> </div> <div id="image2"> <INPUT type="submit" class="myButton2" value="" button onclick="showImg( 'b', 'a', 'c', 'd' )"></button> <img id="b" src="Website Photos/scannedimages/remembrancemaple.jpg" width="220" height="116.895" style="display:none" alt="B" /> </div> <div id="image3"> <INPUT type="submit" class="myButton3" value="" button onclick="showImg( 'c', 'a', 'b', 'd' )"></button> <img id="c" src="Website Photos/scannedimages/remembranceoak.jpg" width="220" height="116.895" style="display:none" alt="C" /> </div> <div id="image4"> <INPUT type="submit" class="myButton4" value="" button onclick="showImg( 'd', 'a', 'c', 'd')"></button> <img id="d" src="Website Photos/scannedimages/remembrancepine.jpg" width="220" height="116.895" style="display:none" alt="D" /> </div> 

I'm totally lost. Does something need added to the Javascript to get the third and fourth images to disappear? Any help would be appreciated!

your function accepts two parameters ( strShow, strHide ) but you are passing it 4 ( 'c', 'a', 'b', 'd' ). so its ignoring the last 2 and thats why your photos arent disappearing. eg when you click on image 3, image C (the first param) is shown and image B (second param) is hidden. but if the photo being displayed is D or A, it wont hide it.

Try

<div id="image3">
<INPUT type="submit" class="myButton3" value="" button onclick="showImg('c', 'd')"></input>  
<img id="c" src="Website Photos/scannedimages/remembranceoak.jpg" width="220" height="116.895" style="display:none" alt="C" /> 
</div>

<div id="image4">
<INPUT type="submit" class="myButton4" value="" button onclick="showImg('d', 'a')"></input>  
<img id="d" src="Website Photos/scannedimages/remembrancepine.jpg" width="220" height="116.895" style="display:none" alt="D" /> 
</div>

Note showIgm only takes two parameters.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM