javascript - 在动态元素上添加类

标签 javascript jquery css

我有一个类,当我添加它时它会激事件画 通过使用ajax,我创建了主题列表,之后我尝试为每个 li 元素添加类,并有延迟,所以看起来每秒都会有一个新主题添加到列表中,但它不起作用。

CSS 文件包含执行动画的 SlideExpandUp 类(效果很好)

js代码如下:

$(document).ready(function(){
  GetTopics();
  AnimateEvent();
});


function GetTopics() {
  $.ajax({
    url: '/Main/GetTopics',
    dataType: "json",
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
      if (data.topics != null) {
        var myTopics = "";

        $.each(data.topics, function (idx, obj) {
          myTopics += "<li class='topic'><a href='#'>" + obj.Topic + "</a></li>";
        });

        $("#topics").append(myTopics);
      }
      else {
        alert("2");
      }
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
  })
}

function AnimateEvent() {
  setTimeout(function () {
    $("#topics li").each(function () {
      $(this).addClass('slideExpandUp') 
    });
  }, 0);
}

总而言之,我需要知道在创建元素后如何为每个元素添加类,并在每次添加之间有延迟。

谢谢大家。

最佳答案

您可以使用 setInterval() 方法来代替:

var current_index=0;

setInterval(function () {
  activeNextLi(); 
}, 1000); //1 second

function activeNextLi(){
  if(current_index<$("#topics li").length-1)
    current_index++;
  else
    current_index=0;

  $("#topics li").removeClass('slideExpandUp');
  $("#topics li").eq(current_index).addClass('slideExpandUp')
}

这将每秒向所有 li 元素添加类 slideExpandUp,如传递的参数 1000 所示。

希望这有帮助。

var current_index=0;

setInterval(function () {
  activeNextLi(); 
}, 1000); //1 second

function activeNextLi(){
  if(current_index<$("#topics li").length-1)
    current_index++;
  else
    current_index=0;

  $("#topics li").removeClass('slideExpandUp');
  $("#topics li").eq(current_index).addClass('slideExpandUp')
}
.slideExpandUp{
  color:red;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='topics'>
  <li class='slideExpandUp'>topic 1</li>
  <li>topic 2</li>
  <li>topic 3</li>
  <li>topic 4</li>
</ul>

关于javascript - 在动态元素上添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41305659/

相关文章:

javascript - 将 Handlebars 模板抽象为不带 AJAX 的外部文件

javascript - 快速滚动离开悬停触发的弹出窗口不会隐藏弹出窗口

javascript - 是否可以将 jQuery $.when 与 bool 标志一起使用?

HTML+CSS 悬停 Sprite ,不同大小的图标,一个背景位置 CSS

jquery - 如何使用 jQuery 根据 Controller 操作结果有条件地更改 CSS 类?

CSS动画速记属性语法顺序

javascript - 计算两个日期之间的天数

javascript - jQuery 可以绑定(bind)到 iframe 的 onload 事件吗?

javascript - .load jquery 在 Chrome 中不起作用

jquery - 更改 bootstrap 3 下拉菜单的 siblings li 背景颜色