简体   繁体   中英

In JavaScript how would I show only one element at a time

I have created this simple JavaScript code that allows a user to click on elements and then show the user what's hidden.

However right now my code allows the user to click on all the of elements and reveal them all at the same time.

I was wondering if anyone could push me in the right direction?

Here is a demo: http://jsfiddle.net/MTJa5/

var hellos = function(){
    var divClicks = document.getElementsByClassName("clickToShow");
    for(i=0; i < divClicks.length; i++){
        var click = divClicks[i];

        var close = function(){
            var open = false;

            click.addEventListener("click", function(e){
            e.preventDefault();
                if(open){
                    this.childNodes[3].setAttribute("class", "hidden");
                    open = false;
                } else {
                    this.childNodes[3].setAttribute("class", "show");
                    open = true;
                }
            },false);
        }();
    }
}();

试试这个: http : //jsfiddle.net/MTJa5/22/

When you show any one element you need to go through the other divs and hide their elements.

EDIT: see this fiddle: http://jsfiddle.net/spb_/MTJa5/25/

hi buddy gone through your fiddle work and found the below solution..

This is a complete javascript in your fiddle with modification::

var hellos = function(){
    var divClicks = document.getElementsByClassName("clickToShow");
    for(i=0; i < divClicks.length; i++){
        var click = divClicks[i];


        var close = function(){
            var open = false;
            click.addEventListener("click", function(e){
                var divVisible= document.getElementsByClassName("show");
        //alert(divVisible.length);
        for(j=0; j < divVisible.length; j++){
            divVisible[j].setAttribute("class", "hidden");
        }

            e.preventDefault();
                if (open){
               this.childNodes[3].setAttribute("class", "hidden");
                    open = false;
                }else{
                    this.childNodes[3].setAttribute("class", "show");
                    open = true;
                }

            },false);
        }();
    }
}();

Here is the explaination::

on your click event i have found all the div elements with class=show and in a

for loop i have set class=hidden again then rest your code handles the stuff, of displaying the respective div on click

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