JavaScript 在点击时显示和隐藏元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7662247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:06:19  来源:igfitidea点击:

JavaScript show and hide elements on click

javascript

提问by Maurice

Please excuse my ignorance, I have no idea what I'm doing, but I'm trying.

请原谅我的无知,我不知道我在做什么,但我正在努力。

I attempted to figure it out by searching, but it has only yielded a functional result in jQuery. Since this is such a small section, I think it would be better to just use plain vanilla JavaScript instead of loading the entire jQuery library.

我试图通过搜索找出它,但它只在 jQuery 中产生了一个功能结果。由于这是一个很小的部分,我认为最好只使用普通的 JavaScript 而不是加载整个 jQuery 库。

Does anyone know how/if I can accomplish the same functionality below, but with only normal JavaScript? Basically what I am trying to do is when "butt1" is clicked, the unordered list "links" will become hidden and the div "box1" will be shown:

有谁知道我如何/是否可以完成下面相同的功能,但只使用普通的JavaScript?基本上我想要做的是当“butt1”被点击时,无序列表“链接”将被隐藏,div“box1”将被显示:

<html> 
<head> 
   <title>qwerty</title> 
   <style type="text/css"> 
      .box1 {background: red;}
   </style> 
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> 
   <script type="text/javascript"> 
      $("#butt1").live("click", show_box1);
      function show_box1(event) {
          $("#links").css("display", "none");
          $(".box1").css("display", "inline");            
      }
  </script> 
</head> 
<body> 
   <ul id="links"> 
      <li id="butt1"><a href="#">blah</a></li> 
      <li id="butt2"><a href="#">blah</a></li> 
      <li id="butt3"><a href="#">blah</a></li> 
   </ul> 
   <div class="box1" style="display: none;">You clicked butt1!</div> 
</body> 
</html>

Here's a link to the above as a working example: http://jsbin.com/umitef/4/-- this is the functionality I want replicated.

这是一个指向上述内容的链接,作为一个工作示例:http: //jsbin.com/umitef/4/——这是我想要复制的功能。

My extended thanks to anyone who takes a moment.. :-)

我要感谢任何花一点时间的人.. :-)

回答by James Allardice

You can use getElementByIdto select an element using an id(equivalent to $("#something")), and getElementsByClassNameto select elements based on class name (equivalent to $(".something")), and you can use the styleproperty to set the displaystyle (equivalent to the jQuery .cssmethod):

您可以使用getElementById来选择使用的元素id(相当于$("#something")),并getElementsByClassName基于类名(相当于选择元素$(".something")),并且可以使用style属性来设置display样式(相当于jQuery的.css方法):

var boxes = document.getElementsByClassName("box1");
document.getElementById("butt1").onclick = function() {
    document.getElementById("links").style.display = "none";
    for(var i = 0; i < boxes.length; i++) {
        boxes[i].style.display = "inline";
    }
}

Note however that getElementsByClassNameis not supported in older versions of IE, which is why jQuery can be useful even for small things - it shortens the code and irons out all the annoying little browser differences.

但是请注意getElementsByClassName,旧版本的 IE 不支持它,这就是为什么 jQuery 甚至可以用于小事情的原因 - 它缩短了代码并消除了所有令人讨厌的浏览器差异。

Also, one major difference between the above code and your jQuery is the use of the .livejQuery method, which monitors the DOM and attaches the event to any element matching the selector, whether it was in the DOM already or it gets added in the future. With the above code, if there is not already an element with id"butt1" in the DOM when the code runs, you will get a TypeError, because getElementByIdwill return null.

此外,上述代码和您的 jQuery 之间的一个主要区别是使用了.livejQuery 方法,该方法监视 DOM 并将事件附加到与选择器匹配的任何元素,无论它已经在 DOM 中还是在将来添加。使用上面的代码,如果id代码运行时DOM中还没有带有“butt1”的元素,你会得到一个TypeError,因为getElementById会返回null.

回答by Mike Thomsen

$("#links").css("display", "none");

Could become:

可以变成:

document.getElementById('links').style.display = 'none';

Realistically, loading jQuery makes a lot of sense since you're doing it from the Google CDN. A lot of sites use that so there is a good probability that at some point at least some of your users have already downloaded it. Plus, jQuery compressed is a very small download. So much so that the readability of jQuery style code is worth it.

实际上,加载 jQuery 很有意义,因为您是从 Google CDN 加载的。许多网站都使用它,因此很有可能在某个时候至少您的一些用户已经下载了它。另外,jQuery 压缩版下载量非常小。如此之多以至于 jQuery 样式代码的可读性是值得的。

回答by Eganr

Ok, while the easiest way is to do it jQuery style you can still replicate that functionality in Javascript.

好的,虽然最简单的方法是使用 jQuery 样式,但您仍然可以在 Javascript 中复制该功能。

The key here is the getElementByIdfunction to grab the specific element you want to manipulate and then you simply set the element.style.displayproperty to 'none'when you want to hide it and 'block'or 'inline'when you want to show it (depending on the context)

这里的关键是的getElementById函数来抓住你要处理的特定元素,然后你只需设置element.style.display属性为“无”,当你想隐藏它,“块”“内联”当你想显示它(取决于上下文)

Here is my crack at it...

这是我的破解...

<head>
<title>qwerty</title> 
<style type="text/css"> 
    #box1 {background: red;}
    #box2 {background: blue;}
    #box3 {background: yellow;}
</style>

<script type="text/javascript">
function toggle_visibility(id) {
    var ul = document.getElementById('links');
    var box = document.getElementById(id);
    if(ul.style.display == 'none')
    {
        ul.style.display = 'block';
        box.style.display = 'block';
    }
    else
    {
        ul.style.display = 'none';
        box.style.display = 'block';
    }
}
</script>
</head>
<body>

<ul id="links"> 
    <li id="butt1"><a href="#" onclick="toggle_visibility('box1');">blah</a></li> 
    <li id="butt2"><a href="#" onclick="toggle_visibility('box2');">blah</a></li> 
    <li id="butt3"><a href="#" onclick="toggle_visibility('box3');">blah</a></li> 
</ul> 
    <div id="box1" style="display: none;">You clicked butt1!</div>
    <div id="box2" style="display: none;">You clicked butt2!</div> 
    <div id="box3" style="display: none;">You clicked butt3!</div> 
</body>

</html>

回答by lumberHymaned

The production compressed version of Jquery is only 31KB. Load it through http://code.google.com/apis/libraries/devguide.html#jquery. You dont have to load the UI if you dont need it. The amount of code to do what you want isnt worth the ease in Jquery. Plus like JamWaffles said if there are other places that you will use Jquery then just load it and use it.

Jquery 的生产压缩版本只有 31KB。通过http://code.google.com/apis/libraries/devguide.html#jquery加载它。如果不需要,则不必加载 UI。做你想做的事情的代码量不值得在 Jquery 中轻松。另外就像 JamWaffles 说的,如果还有其他地方您将使用 Jquery,那么只需加载它并使用它。

回答by megakorre

this is asuming that you only have one box

这是假设你只有一个盒子

window.onload = function() {
 var links = document.getElementById("links"),
     box1  = document.getElementsByClassName("box1")[0];

 links.onclick = function() {
  links.style.display = "none";
  box1.style.display = "inline";
 };
};