简体   繁体   English

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

[英]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. 我有几个Div,其中包含我想根据下拉列表中的选择显示的列表。 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? 为了不必更新每个块隐藏然后显示我想要的那个是一个外卡方法或方式我可以简单地使用一个数组定义我的Divs循环通过隐藏/显示?

basis of what I was building. 我正在建设的基础。 Planned on converting to a switch statement instead of a series of If statements. 计划转换为switch语句而不是一系列If语句。

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/ http://jsfiddle.net/ak95K/3/

You can use CSS to control what to display: http://jsfiddle.net/DerekL/ak95K/5/ 您可以使用CSS来控制要显示的内容: 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. PS:IE 9或更早版本不支持classList However for this case you can just do c.className = "this.value" . 但是对于这种情况,你可以只做c.className = "this.value" Or just go for jQuery 'cause it solves every problem in the Universe. 或者只是去jQuery,因为它解决了宇宙中的每一个问题。

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

CSS CSS

.hide {
    display: none;
}

HTML 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 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 Working Code 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');
        }
    };
}()));

On jsFiddle jsFiddle上

Update: Adding options 更新:添加options

CSS 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 使用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 jsFiddle上

If you were writing without the need to support older browsers, then it would look like this. 如果你在不需要支持旧版浏览器的情况下编写,那么它就像这样。

Javascript 使用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 jsFiddle上

HTML HTML

Make your divs part of a particular class (.my). 让你的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 CSS

Only show that class when it is accompanied by another class (.selected). 只有当它附带另一个类(.selected)时才显示该类。

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

JavaScript JavaScript的

Add and remove that class (.selected) appropriately. 适当地添加和删除该类(.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');
                }
            });
    });

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. 您还可以通过跟踪先前选择的元素来删除整个事物,并仅从前一个元素中删除.selected类,而不是从所有元素中删除。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM