[英]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.