简体   繁体   中英

Javascript function that changes various images onclick of one image

I have searched and tried out various functions including 'if' and 'else' functions, but I can't get them to work..

The intention is to change various images onclick of just one image. Here is the HTML for that image I'm currently using:

<div id="apDiv2"><a href="#" onclick="changeImg();"><img src="images/AJP-TAG-W.jpg" width="207" height="138" /></a></div>

I would like onclick of that image for these two images to be swapped

<div id="apDiv12"><a href="dancehall.html"><img src="images/Dancehall.jpg" width="240" height="74" alt="Dancehall" id="Dancehall" /></a></div>

and

<div id="apDiv6"><a href="house.html"><img src="images/House.jpg" width="240" height="74" alt="House" id="House" /></a></div>

I recommend using jQuery ( https://code.jquery.com ) and using the following function:

function changeImg()
{
    var tmp_src = $("#Dancehall").attr("src");
    $("#Dancehall").attr("src", $("#House").attr("src"));
    $("#House").attr("src", tmp_src);
}

Or the basic javascript solution:

function changeImg()
{
    var tmp_src = document.getElementById("Dancehall").src;
    document.getElementById("Dancehall").src = document.getElementById("House").src;
    document.getElementById("House").src = tmp_src;
}

You can hide or show your divs with jQuery or basic Javascript. Here is an jQuery example for you;

<div id="apDiv2"><a href="#" onclick="changeImg();"><img src="images/AJP-TAG-W.jpg" width="207" height="138" /></a></div>
<div style="display:none" id="apDiv12"><a href="dancehall.html"><img src="images/Dancehall.jpg" width="240" height="74" alt="Dancehall" id="Dancehall" /></a></div>
<div style="display:none" id="apDiv6"><a href="house.html"><img src="images/House.jpg" width="240" height="74" alt="House" id="House" /></a></div>
    <script>
    function changeImg(){
        $('#apDiv2').hide();
        $('#apDiv6').show();
        $('#apDiv12').show();
    }
    </script>
function changeImg() {
    var img1 = document.getElementById('apDiv12');
    var img2 = document.getElementById('apDiv6');
    var tmp = img1.innerHTML;
    img1.innerHTML = img2.innerHTML;
    img2.innerHTML = tmp;
}

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