类category2
,category3
,category4
等是动态创建的。我想添加和删除一些称为active
的类,例如class="category2 active"
。
这是我尝试将.active类添加到动态创建的类dynamic-class *中的代码,但是它不起作用:
if (count == 1) {
$('.dynamic-class' + count).removeClass('active');
$('.dynamic-class' + 2).addClass('active');
}
if (count == 2) {
$('.dynamic-class' + count).removeClass('active');
$('.dynamic-class' + 1).addClass('active');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="film_listing live_tv">
<div class="col-sm-2"><img id="11665" class="dynamic-class1" src="images/movies/flowerstv.jpg"></div>
<div class="col-sm-2"><img id="11666" class="dynamic-class2" src="images/movies/flowerstv.jpg"></div>
</div>
最佳答案
按类名选择时缺少.
。请尝试以下方法:
if (count == 1) {
$('.dynamic-class' + count).removeClass('active');
count++;
$('.dynamic-class' + count).addClass('active');
}
if (count == 2) {
$('.dynamic-class' + count).removeClass('active');
count--;
$('.dynamic-class' + count).addClass('active');
}
关于javascript - 如何将类添加到动态创建的DOM元素或类中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52293643/