[英]Add class on dynamic elements
我有一个类,当我添加它时,它使用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')
}
这将在传递的参数1000
显示时slideExpandUp
向所有li
元素添加类slideExpandUp
。
希望这可以帮助。
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>
尝试将您的事件在AnimateEvent函数下作为委托事件,并使用setInterval这可以帮助您。
JAVASCRIPT代码:
function AnimateEvent() {
setInterval(function () {
$('body').find("#topics li").each(function () {
$(this).addClass('slideExpandUp')
});
}, 100);
}
在你的情况下,函数AnimateEvent
没有任何影响,因为函数GetTopics
是一个异步调用,它将在未来一段时间后完成。 在DOM中添加任何内容之前调用AnimateEvent
。
因此,解决方案是将函数作为回调传递,并在完成追加时调用它。
$(document).ready(function() {
GetTopics(AnimateEvent); // <---pass the function as callback here.
});
function GetTopics(callback) {
$.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");
}
callback(); //<----call that function here.
},
error: function(xhr) {
alert(xhr.responseText);
}
})
}
function AnimateEvent() {
$("#topics li").each(function() {
$(this).addClass('slideExpandUp')
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.