简体   繁体   English

如何使用JavaScript隐藏多个元素

[英]How to hide multiple elements using javascript

Yes, the question has been asked so many times, but this one is a bit more specific. 是的,这个问题已经问了很多遍了,但是这个问题更具体了。 I need JavaScript code that shows/hides all elements of a certain class . 我需要显示/隐藏某个class所有元素的JavaScript代码。 The code must be compatible with the older browsers and Internet Explorer, and it must have an extremely small footprint. 该代码必须与旧版浏览器和Internet Explorer兼容,并且必须占用非常小的空间。 So, please don't post jQuery solutions, since this task will use 0.01% of the code from the library. 因此,请不要发布jQuery解决方案,因为此任务将使用库中0.01%的代码。 So far I've come up with this: 到目前为止,我已经提出了:

var flip = document.getElementsByTagName(_tag);
if (trigger)
  for (var i = 0; i < flip.length; i++)
    if (flip[i].className == _class) flip[i].style.visibility = 'visible';
    else
      for (var i = 0; i < flip.length; i++)
        if (flip[i].className == _class) flip[i].style.visibility = 'hidden';

Since getElementsByclassName does not work in IE, and most common solutions are too bulky for me. 由于getElementsByclassName在IE中不起作用,因此大多数常见的解决方案对我来说都太大了。 Is this code optimal for the task, or could it be streamlined even more? 此代码是针对任务的最佳代码,还是可以进一步简化? (as a reference, the previous solution used a cgi to add <style>.myclass {visibility:visible}</class> to the page) (作为参考,以前的解决方案使用cgi<style>.myclass {visibility:visible}</class>到页面中)

Don't use the same iterator (var i) in an inner for loop because it collides with your current loop. 不要在内部for循环中使用相同的迭代器(var i),因为它会与当前循环冲突。 Remove the second inner one and check if class x is set, then set your property, do a "continue" and vice versa: 删除第二个内部的,检查是否设置了类x,然后设置属性,执行“继续”,反之亦然:

var flip = document.getElementsByTagName(_tag);
if (trigger) {
  for (var i = 0; i < flip.length; i++) {
    var state = flip[i].style.visibility;
    if (flip[i].className == _class && state == 'hidden') {
      flip[i].style.visibility = 'visible';
      continue;
    }

    if (flip[i].className == _class && state == 'visible') {
      flip[i].style.visibility = 'hidden';
    }
  }
}

Here's a mockup of a classname-switcher, would that be an idea? 这是一个类名切换器的模型,这是个主意吗? If you use IE < 8, use document.getElementsByTagName instead of document.querySelectorAll . 如果使用IE <8,请使用document.getElementsByTagName而不是document.querySelectorAll

 (function() { document.querySelector('button').addEventListener('click', toggledivshidden); function toggledivshidden() { return toggle('div', 'hidden'); } function toggle(tag, clssname) { var flips = document.querySelectorAll(tag); for (var i = 0; i< flips.length; i+=1) { var classExists = RegExp(clssname, 'i').test(flips[i].className); classEdit(flips[i], clssname, classExists); } } // add or remove a classname, without destroying other classnames function classEdit(el, clname, remove) { var re = RegExp(clname, 'g'), current = el.className; el.className = ( remove ? current.replace(re, '') : re.test(current) ? current : current +' '+clname ) .replace(/\\s+/g, ' ') // remove redundant spaces .replace(/^\\s+|\\s+$/,''); // trim return true; } }()) 
 .hidden { visibility: collapse; height: 0; } div:after { content: ' - className: "'attr(class)'"'; color: #c0c0c0; } 
 <div class="hidden some">originally hidden</div> <div class="some hidden foo bar">originally hidden</div> <div class="some more etc">originally visible</div> <div class="some">originally visible</div> <button>toggle</button> 

You need to use a shim or iterate through the dom and get elements with your class. 您需要使用垫片或遍历dom并在您的课程中获取元素。 See no other solutions. 看不到其他解决方案。

I agree with Luba, here's a shim: getElementsByClassName.polyfill.js 我同意Luba,这是一个补片: getElementsByClassName.polyfill.js

As commented by Hemang, link only answers are invalid due to link change so here's the code from the link. 正如Hemang所说,仅链接的答案由于链接更改而无效,因此这是链接中的代码。 The link is a shim for the deficit of getElementsByClassName in pre-ie9. 该链接是pre-ie9中getElementsByClassName不足的一个垫片。 Initially the shim tests the lack of getElementsByClassName then tests for the presence of querySelectorAll, if this is not available (ie pre-ie8) then evaluate is used. 最初,填充程序会测试getElementsByClassName的缺失,然后测试querySelectorAll的存在,如果不可用(即pre-ie8),则使用评估。

// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License

if (!document.getElementsByClassName) {
  document.getElementsByClassName = function(search) {
    var d = document, elements, pattern, i, results = [];
    if (d.querySelectorAll) { // IE8
      return d.querySelectorAll("." + search);
    }
    if (d.evaluate) { // IE6, IE7
      pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
      elements = d.evaluate(pattern, d, null, 0, null);
      while ((i = elements.iterateNext())) {
        results.push(i);
      }
    } else {
      elements = d.getElementsByTagName("*");
      pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
      for (i = 0; i < elements.length; i++) {
        if ( pattern.test(elements[i].className) ) {
          results.push(elements[i]);
        }
      }
    }
    return results;
  }
}

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

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