简体   繁体   中英

Javascript - Show/hide pictures with buttons

I would like to improve my script so I can have more buttons which can show one image each. (I need 49 buttons). At the moment I only have two well working buttons. How should I write my script below so I can make 49 buttons?

JavaScript

<script type="text/javascript" language="javascript">
    function showHide() {
        var ele = document.getElementById("showHideDiv");
        var ele1 = document.getElementById("showHideDiv1");
        ele1.style.display = "none";
        if(ele.style.display == "block") {
                ele.style.display = "none";             
          }
        else {
            ele.style.display = "block";            
        }
    }

function showHide1() {
    var ele = document.getElementById("showHideDiv");
    var ele1 = document.getElementById("showHideDiv1");
    ele.style.display = "none";
    if(ele1.style.display == "block") {
            ele1.style.display = "none";
      }
    else {
        ele1.style.display = "block";
    }
}
</script>

HTML

<button onclick="return showHide();">box1</button>
<button onclick="return showHide1();">box2</button>
<div id="showHideDiv" style="display:none;"><img  src="1.gif" height="280" width="120"/></div>
<div id="showHideDiv1" style="display:none;"><img  src="2.gif" height="280" width="120"/></div>

The showHide() can receive a parameter with the div id.

function showHide(my_id) {
    var ele = document.getElementById("showHideDiv" + my_div);
    if(ele.style.display == "block") {
            ele.style.display = "none";             
    }
    else {
        ele.style.display = "block";            
    }
}

What lacks in this code is to hide all the other divs.

Well, this is another approach, using jQuery (I know, I know, but I just can't make it work on pure javascript). I've used the following markup:

<div id="template">
    <button class="toggleButton"></button>
    <div class="showHideDiv"><img src="" height="280" width="120"/></div>
</div>
<div id="main">
</div>

Div template is used as template for other divs. Here is javascript code:

var main = $('#main');
// copy template to make 49 images.
var template = $('#template');
for (var i= 0; i < 49; i++) {
    var div = template.clone();
    var img = main.find('img');
    var button = div.find('button');
    img.attr('src', i + '.gif');
    button.text('box'+(i+1));   
    main.append(div.html());    
}
// add toggle event handler
$(document).on("click", ".toggleButton", function(e) {
    $('.showHideDiv').hide();
    $(e.target).next('.showHideDiv').show();
});

Here is demo . It has a lot of errors in console, since there are no real images there, but that should be ok in real application.

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