如何将类添加到动态创建的DOM元素或类中

时间:2018-09-12 11:04:55

标签: javascript jquery html dynamic

动态创建类category2category3category4等。我想添加和删除一些名为active的类,例如class="category2 active"

这是我尝试将.active类添加到动态创建的类<​​strong> 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>

1 个答案:

答案 0 :(得分:4)

按类名选择时,您缺少.。请尝试以下:

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');
}