$(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。此处的代码似乎不起作用。
最佳答案
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/