Javascript 点击一张图片改变不同图片的函数

Javascript function that changes various images onclick of one image

我已经搜索并尝试了各种功能,包括 'if' 和 'else' 功能,但我无法让它们工作..

目的是通过单击一张图片来更改各种图片。这是我当前使用的图像的 HTML:

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

我想单击该图像以交换这两张图像

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

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

我建议使用 jQuery (https://code.jquery.com) 并使用以下函数:

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

或者基本的javascript解决方案:

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

您可以使用 jQuery 或基本 Javascript 隐藏或显示您的 div。 这里有一个 jQuery 例子给你;

<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;
}