jquery - 如何切换显示 :none, display:block

标签 jquery html css

$(document).ready(function() {
  ('.button').click(function() {
    let item = $(this).closest('item');
    if (item.css.('display') === 'none') {
      item.show();
      item.css('display', 'block');
    } else if (item.css.('display') === 'block') {
      item.hide();
      item.css('display', 'none');
    }
  });
});
.item {
  display: none;
}
<div class="container">
  <button class="button">Click</button>
  <div class="front">front page</div>
  <div class="item">
    This is a paragraph with little content. This is another small paragraph.
  </div>
</div>

目的是在单击按钮时隐藏和显示当前 div。我有相同的容器具有相同的类名。如果我使用简单的切换按钮,单击按钮后,所有其他容器都会被切换。在这种情况下,只有当前容器必须显示和隐藏。类容器的第一个 div 子项最初显示,第二个 div 子项隐藏/显示:无。单击按钮后,显示第二个 div 子项,display:none 更改为 display:block。此处的代码似乎不起作用。

最佳答案

使用.siblings()

Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.

工作片段:-

$(document).ready(function() {
  $('.button').click(function() {
    $(this).siblings(".item").toggle();
  });
});
.item {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button class="button">Click</button>
  <div class="front">front page</div>
  <div class="item">
    This is a paragraph with little content. This is another small paragraph.
  </div>
</div>

关于jquery - 如何切换显示 :none, display:block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48314162/

相关文章:

javascript - 如何将 Jquery Chaining 应用于多父方法

html - 下拉菜单显示菜单和子菜单之间的差距?

HTML 方向属性不起作用

jquery - IE 中非常奇怪的 url,页面 404 错误

html - Div 占据了容器的整个高度,但仍位于底部

html - 我的页脚 div 无法连接到页面左侧,其他 div 崩溃

javascript - 禁用与我的站点冲突的 chrome 扩展

jQuery 相当于 PHP 的 file_exists()?

jquery - 如何将 DOM 对象的引用传递给 jQuery 函数?

javascript - 如何为表格行设置动画