我想使用 jQuery 為每一行分配一個數字。如果元素有隱藏類,則忽略它并自動對數字進行排序。
<style>
:before{
display:block;
margin-top:10px;
font: inherit;
}
.tc-hidden{
display:none;
}
.tc1 h3.tm-section-label:before {
content: "1";
}
.tc2 h3.tm-section-label:before {
content: "2";
}
.tc3 h3.tm-section-label:before {
content: "3";
}
.tc4 h3.tm-section-label:before {
content: "4";
}
</style>
<div class="tc-cell tc1">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc2 tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc3 tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc4">
<h3 class="tm-section-label"></h3>
</div>
眾所周知,最后一個元素必須顯示數字 2 但它顯示數字 4
uj5u.com熱心網友回復:
您可以遍歷.tc-cell元素并確定它們是否被隱藏,并動態調整它們的tc-<n>類名:
let i = 1; // Starting index number for tc<i> class name to use
$('.tc-cell').each(function(){
// Remove all tc-<n> classes from this tc-cell
// See https://stackoverflow.com/a/5182103/378779
$(this).removeClass (function (index, className) {
return (className.match (/(^|\s)tc\d /g) || []).join(' ');
});
// If we should not be hidden, add a class of tc<i> and increment i:
if ( ! $(this).hasClass('tc-hidden') ) {
$(this).addClass('tc' i );
}
});
:before{
display:block;
margin-top:10px;
font: inherit;
}
.tc-hidden{
display:none;
}
.tc1 h3.tm-section-label:before {
content: "1";
}
.tc2 h3.tm-section-label:before {
content: "2";
}
.tc3 h3.tm-section-label:before {
content: "3";
}
.tc4 h3.tm-section-label:before {
content: "4";
}
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<div class="tc-cell tc1">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc2 tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc3 tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc4">
<h3 class="tm-section-label"></h3>
</div>
uj5u.com熱心網友回復:
您可以洗掉類別,tc1 tc2 tc3 tc4如果每個專案都沒有,tc-hidden您可以添加適當的類別。
var count=0;
$.each($(".tc-cell"),(index,item)=>{
if(!$(item).hasClass("tc-hidden"))
$(item).addClass("tc" ((index 1)-count));
else
count ;
});
<style>
:before{
display:block;
margin-top:10px;
font: inherit;
}
.tc-hidden{
display:none;
}
.tc1 h3.tm-section-label:before {
content: "1";
}
.tc2 h3.tm-section-label:before {
content: "2";
}
.tc3 h3.tm-section-label:before {
content: "3";
}
.tc4 h3.tm-section-label:before {
content: "4";
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tc-cell ">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell tc-hidden">
<h3 class="tm-section-label"></h3>
</div>
<div class="tc-cell">
<h3 class="tm-section-label"></h3>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498388.html
標籤:javascript jQuery css
