更改选择时更好的方式来编写javascript hide / show div

时间:2014-04-21 21:32:21

标签: javascript html

有没有更好的方法来写这样的东西。我有几个Div,其中包含我想根据下拉列表中的选择显示的列表。为了不必更新每个块来隐藏然后显示我想要的那个是一个外卡方法或方式我可以简单地使用一个数组定义我的Divs循环以进行隐藏/显示?

我正在建设的基础。计划转换为switch语句而不是一系列If语句。

我不喜欢这部分。

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用CSS来控制要显示的内容:http://jsfiddle.net/DerekL/ak95K/5/

有很多方法可以做到这一点。这是我最喜欢的那个:

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:IE 9或更早版本不支持classList。但是对于这种情况,您可以c.className = "this.value"。或者只是去寻找jQuery,因为它解决了宇宙中的每一个问题。

答案 1 :(得分:1)

如果我需要支持较旧的(但不是古老的)浏览器(并且不使用jQuery),就像你说的那样,那么我会做这样的事情。

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跨浏览器支持代码

(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工作代码

$.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');
        }
    };
}()));

jsFiddle

更新:添加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');
            }
        }
    };
}()));

jsFiddle

如果您在不需要支持旧版浏览器的情况下编写文章,那么它就会像这样。

的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);

jsFiddle

答案 2 :(得分:0)

HTML

让你的div成为特定类(.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

只有当它附带另一个类(.selected)时才显示该类。

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

的JavaScript

适当地添加和删除该类(.selected)。

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

你也可以通过跟踪之前选择的元素来砍伐整个事物,只从前一个元素中删除.selected类,而不是全部。

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