隐藏具有相同类名的所有元素?

use*_*970 21 javascript

我试图隐藏具有相同类名(float_form)的元素,但我也尝试使用下面的脚本来显示它们(所有的float_form类div最初都是隐藏的).我已经看了很多jquery解决方案,但我似乎无法让它们中的任何一个工作.

function show(a) {
    var e = document.getElementById(a);
    if (!e) 
        return true;

    if (e.style.display == "none") {
        e.style.display = "block"
    } else {
        e.style.display = "none"
    }
    return true;
}
?
Run Code Online (Sandbox Code Playgroud)

编辑:对不起,如果不清楚,我不打算使用Jquery(我知道这不是jquery).我正在寻找一种方法来使用javascript来识别不在style = display:none中的重复类名.在不影响show/hide ID元素的情况下,因为有一个以div id为键的循环.div的html如下所示,{item.ID}是while循环.

 <div class="float_form" id="{item.ID}" style="display: none;"> 
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 54

香草javascript

function toggle(className, displayState){
    var elements = document.getElementsByClassName(className)

    for (var i = 0; i < elements.length; i++){
        elements[i].style.display = displayState;
    }
}

toggle('float_form', 'block'); // Shows
toggle('float_form', 'none'); // hides
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$('.float_form').show(); // Shows
$('.float_form').hide(); // hides
Run Code Online (Sandbox Code Playgroud)

  • @undefined.那很烦人,人们希望你把它们当作自己的工作,甚至不花时间说出自己想要的东西.[听起来像是对我的帮助吸血鬼](http://slash7.com/2006/12/22/vampires/) (3认同)
  • 你是对的,这是令人沮丧的,特别是当他们提出问题并在下周回来检查答案时,试图解决问题的人正在互相争斗. (2认同)

0x4*_*2D2 7

如果您正在研究jQuery,那么很高兴知道您可以在的参数内使用类选择器$并调用method .hide()

$('.myClass').hide(); // all elements with the class myClass will hide.
Run Code Online (Sandbox Code Playgroud)

但是,如果您要寻找的是拨动开关,请使用 .toggle();

但是,这是我在使用jQuery的情况下进行良好切换的观点:

function toggle( selector ) {
  var nodes = document.querySelectorAll( selector ),
      node,
      styleProperty = function(a, b) {
        return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
      };

  [].forEach.call(nodes, function( a, b ) {
    node = a;

    node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
  });

}

toggle( '.myClass' );
Run Code Online (Sandbox Code Playgroud)

此处的演示(单击“渲染”以运行):http : //jsbin.com/ofusad/2/edit#javascript,html