如果其子元素ul元素没有可见的li元素,我在这里尝试隐藏字段集。
示例代码:
$(document).ready(function () {
$('.readBtn').click(function () {
var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');
$('#chapter_'+chapterID).slideUp();
});
})

button.readBtn {
margin-left: 1em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="story">
<legend>
<a href="#" target="_blank">
Title 1
</a>
</legend>
<ul>
<li class="chapter" id="chapter_9">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_9">
Mark as Read
</button>
</li>
</ul>
</fieldset>
<fieldset class="story">
<legend>
<a href="#" target="_blank">
Title 2
</a>
</legend>
<ul>
<li class="chapter" id="chapter_10">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_10">
Mark as Read
</button>
</li>
<li class="chapter" id="chapter_12">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_12">
Mark as Read
</button>
</li>
</ul>
</fieldset>
&#13;
我不确定如何去做我想做的事情。我看过jquery selector question: do something only if all elements are hidden,但我不确定如何使用我的代码。看起来答案是在我需要的正确轨道上,但我对如何改变它感到迷茫。
答案 0 :(得分:1)
尝试在.slideUp()
使用回调来选择,.hide()
.closest()
fieldset
$(document).ready(function () {
$('.readBtn').click(function () {
var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');
$('#chapter_'+chapterID).slideUp(function() {
if (!$(this).is(":visible")
&& !$(this).siblings("li").is(":visible")) {
// hide `fieldset`
$(this).closest("fieldset").hide()
}
});
});
})
$(document).ready(function () {
$('.readBtn').click(function () {
var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');
$('#chapter_'+chapterID).slideUp(function() {
if (!$(this).is(":visible") && !$(this).siblings("li").is(":visible")) {
$(this).closest("fieldset").hide()
}
});
});
})
button.readBtn {
margin-left: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="story">
<legend>
<a href="#" target="_blank">
Title 1
</a>
</legend>
<ul>
<li class="chapter" id="chapter_9">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_9">
Mark as Read
</button>
</li>
</ul>
</fieldset>
<fieldset class="story">
<legend>
<a href="#" target="_blank">
Title 2
</a>
</legend>
<ul>
<li class="chapter" id="chapter_10">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_10">
Mark as Read
</button>
</li>
<li class="chapter" id="chapter_12">
<a href="#" target="_blank">
Chapter Title
</a>
<button class="readBtn" id="readBtn_12">
Mark as Read
</button>
</li>
</ul>
</fieldset>
答案 1 :(得分:1)
它将隐藏最近的字段集(仅当字段集没有可见的li元素时)
$(document).ready(function () {
$('.readBtn').click(function () {
var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');
$('#chapter_'+chapterID).slideUp(function() {
if ($("li.chapter:visible").length == 0) {
// hide `fieldset`
$(this).closest("fieldset").hide()
}
});
});
})