我有一个类,当我添加它时它会激事件画 通过使用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/