使用相同名称切换div可见性

时间:2014-03-28 17:11:26

标签: javascript html

我有一个脚本来切换div可见性,但它只显示第一个div,而不显示其他div。

<div id="toggle">Toggle</div>
<div id="to_toggle">1</div>
<div id="to_toggle">2</div>

如何为此创建脚本?

2 个答案:

答案 0 :(得分:1)

理由是你从不暗示jQuery应该或者可以使用,我想我会提供一个简单的&#39; JavaScript替代方案(虽然可能仅适用于最新的浏览器):

// extending the prototype of a basic HTMLElement, adding a named method:
HTMLElement.prototype.toggle = function (toggleClass) {
    // calling the Array.prototype.forEach method to iterate over an array/collection:
    // using the collection returned by 'document.querySelectorAll()'
    [].forEach.call(document.querySelectorAll('.' + toggleClass), function(a){
        // a is the DOM node over which we're currently iterating:
        a.style.display = a.style.display == 'none' ? 'block' : 'none';
    });
};

// getting the element we wish to use to activate the 'toggle()' method,
// adding an event listener (listening for the 'click' event), and then
// calling an anonymous function:
document.getElementById('toggle').addEventListener('click', function(){
    // 'this' here is the element we retrieved earlier,
    // and we call the 'toggle()' method, supplying the
    // name of the class we want to toggle:
    this.toggle('to_toggle');
});

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

您不能多次使用ID,这就是所用的类。

<div id="toggle">Toggle</div>
<div class="to_toggle">1</div>
<div class="to_toggle">2</div>

javascript版本:

document.getElementById('toggle').onclick = function(){
    var elements2toggle = document.getElementsByClassName('to_toggle');
    var current = elements2toggle[0].style.display;
    var setTo = current=='none' ? 'block' : 'none';
    var loopLength = elements2toggle.length;
    for(i=0; i<loopLength; i++){
        elements2toggle[i].style.display = setTo;
    }
};

和jQuery版本。如您所见,它更容易阅读。不要仅仅为这部分使用jQuery,看看你是否可以更广泛地使用它,它有很多功能。

$('#toggle').on('click', function(){
    $('.to_toggle').toggle(); // now use the class to toggle
});

大卫让我做基准测试(今天学到了另一个网站;)),结果如下:
http://jsperf.com/fastest-method-to-toggle-items

似乎使用jQuery来检查当前显示是否比.toggle()更快,所以我对此做了更正(我对答案的评论之一另有说法)