简体   繁体   中英

Better way to write javascript hide/show div on change of select

Is there a better way to write something like this. I have a couple Divs that have lists in them that I want to display based on the selection in a drop down. for the sake of not having to update each block to hide then show the one I want is there a wild card approach or way I can simply use an array defining my Divs to loop through for hide/display?

basis of what I was building. Planned on converting to a switch statement instead of a series of If statements.

I am not liking this portion primarily.

document.getElementById('my1').style.display = 'block';
document.getElementById('my2').style.display = 'none';
document.getElementById('my3').style.display = 'none';

http://jsfiddle.net/ak95K/3/

You can use CSS to control what to display: http://jsfiddle.net/DerekL/ak95K/5/

There are many ways to do it. This is the one I prefer the most:

document.querySelector("select").addEventListener("change", function(){
    var c = document.querySelector("#display");
    c.className = "";
    c.classList.add(this.value);
});

.my1 > :not(#my1){
    display: none;
}
.my2 > :not(#my2){
    display: none;
}

PS: classList is not supported by IE 9 or earlier. However for this case you can just do c.className = "this.value" . Or just go for jQuery 'cause it solves every problem in the Universe.

If I needed to support older (but not ancient) browsers (and wasn't using jQuery), like you are saying, then I would do something like this.

CSS

.hide {
    display: none;
}

HTML

<select id="mine">
    <option value="0">Test1</option>
    <option value="1">Test2</option>
</select>
<div id="display1">
    <div>
        <p>Some Text in 1</p>
    </div>
    <div class="hide">
        <p>Some Text in 2</p>
    </div>
</div>

Javascript Cross Browser Support Code

(function () {
    var slice = [].slice,
        nativeTrim = ''.trim,
        trim,
        classList;

    function isFunction(arg) {
        return typeof arg === 'function';
    }

    function isString(arg) {
        return typeof arg === 'string';
    }

    function handler(object, evt, func) {
        var ret;

        if (evt) {
            ret = func.call(object, evt);
            if (false === ret) {
                evt.stopPropagation();
                evt.preventDefault();
            }
        } else {
            window.event.target = window.event.srcElement;
            ret = func.call(object, window.event);
            if (false === ret) {
                window.event.returnValue = false;
                window.event.cancelBubble = true;
            }
        }

        return ret;
    }

    function addEventListener(object, type, func) {
        var uid = type + ':' + func,
            euid = 'e:' + uid;

        object[euid] = func;
        if (isFunction(object.addEventListener)) {
            object[uid] = function (evt) {
                handler(object, evt, object[euid]);
            };

            object.addEventListener(type, object[uid], false);
        } else if (object.attachEvent) {
            object[uid] = function () {
                handler(object, null, object[euid]);
            };

            object.attachEvent('on' + type, object[uid]);
        } else {
            throw new Error('Handler could not be added.');
        }
    }

    if (isFunction(nativeTrim)) {
        trim = function (text) {
            return nativeTrim.call(text);
        };
    } else {
        trim = function (text) {
            return text.replace(/^\s+|\s+$/g, '');
        };
    }

    if ('classList' in document.body) {
        classList = {
            contains: function (node, className) {
                return node.classList.contains(className);
            },

            add: function add(node, className) {
                node.classList.add(className);
            },

            remove: function (node, className) {
                node.classList.remove(className);
            },

            toggle: function (node, className) {
                node.classList.toggle(className);
            }
        };
    } else {
        classList = {
            makeRegex: function (className, flags) {
                return new RegExp('(?:^|\\s)' + className + '(?!\\S)', isString(flags) ? flags : '');
            },

            contains: function (node, className) {
                return !!node.className.match(classList.makeRegex(className));
            },

            add: function add(node, className) {
                if (!classList.contains(node, className)) {
                    node.className = trim(node.className);
                    if (node.className) {
                        node.className += ' ';
                    }

                    node.className += className;
                }
            },

            remove: function (node, className) {
                if (classList.contains(node, className)) {
                    node.className = trim(node.className.replace(classList.makeRegex(className, 'g'), ''));
                }
            },

            toggle: function (node, className) {
                if (classList.contains(node, className)) {
                    classList.remove(node, className);
                } else {
                    classList.add(node, className);
                }
            }
        };
    }

    window.$ = {
        addEventListener: addEventListener,
        classList: classList
    };
}());

Javascript Working Code

$.addEventListener(document.getElementById('mine'), 'change', (function () {
    var children1 = document.getElementById('display1').children,
        length1,
        index;

    return function (evt) {
        for (index = 0, length1 = children1.length; index < length1; index += 1) {
            $.classList.toggle(children1[index], 'hide');
        }
    };
}()));

On jsFiddle

Update: Adding options

CSS

<select id="mine">
    <option value="test1">Test1</option>
    <option value="test2">Test2</option>
    <option value="test3">Test3</option>
</select>
<div id="display1">
    <div>
        <p>Some Text in 1</p>
    </div>
    <div class="hide">
        <p>Some Text in 2</p>
    </div>
    <div class="hide">
        <p>Some Text in 3</p>
    </div>
</div>

Javascript

$.addEventListener(document.getElementById('mine'), 'change', (function () {
    var children1 = document.getElementById('display1').children,
        length1,
        index;

    return function (evt) {
        for (index = 0, length1 = children1.length; index < length1; index += 1) {
            if (index === evt.target.selectedIndex) {
                $.classList.remove(children1[index], 'hide');
            } else {
                $.classList.add(children1[index], 'hide');
            }
        }
    };
}()));

On jsFiddle

If you were writing without the need to support older browsers, then it would look like this.

Javascript

document.getElementById('mine').addEventListener('change', (function () {
    var children1 = document.getElementById('display1').children,
        length1,
        index;

    return function (evt) {
        for (index = 0, length1 = children1.length; index < length1; index += 1) {
            if (index === evt.target.selectedIndex) {
                children1[index].classList.remove('hide');
            } else {
                children1[index].classList.add('hide');
            }
        }
    };
}()), false);

On jsFiddle

HTML

Make your divs part of a particular class (.my).

<select name="mine" id="mine">
    <option value="#my1">Test1</option>
    <option value="#my2">Test2</option>
</select>

<div id="my1" class="my">
    <p>Some Text in 1</p>
</div>

<div id="my2" class="my">
    <p>Some Text in 2</p>
</div>

CSS

Only show that class when it is accompanied by another class (.selected).

.my:not(.selected) {
    display: none;
}

JavaScript

Add and remove that class (.selected) appropriately.

document
    .querySelector('select')
    .addEventListener('change', function () {
        var elements = Array.prototype.slice.call(document.querySelectorAll('.my'), 0),
            target = document.querySelector(this.value);

        elements
            .forEach(function (elem) {
                if (elem === target) {
                    elem.classList.add('selected');
                } else {
                    elem.classList.remove('selected');
                }
            });
    });

You could also deforest the whole thing by tracking the previously selected element and only remove the .selected class from the previous element, instead of all of them.

http://jsfiddle.net/ak95K/7/

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