1
林学习承诺,所以我做了简单的网站,通过ajax生成内容。链接承诺平原javascript
当用户点击链接时,它会更改网站的内容,但首先应该淡出原始内容。
我已经做脚本调用的承诺和回报内容
function getcontent(url){
return new Promise(function(resolve,reject){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload=function(){
if(xhttp.status==200){
resolve(xhttp.response)
}
else{
reject(Error(xhttp.responseText))
}
}
xhttp.send();
})
}
和功能应该添加内容
function change(url){
var doc=document.getElementsByClassName("info")[0];
return getcontent(url).then(function(x){
doc.children[0].classList.add("remove");
return x
}).then(function(x){
doc.removeChild(doc.children[doc.children.length-1]);
var div=document.createElement("div");
div.innerHTML=x;
doc.appendChild(div)
})
}
更清晰,这将有类添加的元素具有
-webkit-transition:15s ease all;
所以我想,让它,原来的内容应该淡出,和船尾呃ajax内容应该被添加到网站上。这就是为什么我使用承诺。我认为承诺链接等待.then()方法来完成,然后执行next.then()方法。但是,在原始内容消失之前,ajax内容会被添加到网站中,因此在第一个.then()方法完成之前调用它。我错过了什么?
我尝试使用ontransitionend事件的评论suggets做两种分离的功能,但它只是不会工作
function getcontent(url){
return new Promise(function(resolve,reject){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload=function(){
if(xhttp.status==200){
resolve(xhttp.response)
}
else{
reject(Error(xhttp.responseText))
}
}
xhttp.send();
})
}
function change(url){
var doc=document.getElementsByClassName("info")[0];
getcontent(url).then(function(x){
return new Promise(function(res,rej){
doc.addEventListener("transitionend",function(){
res(x);
})});
doc.children[0].classList.add("remove")
})
}
即时试图让它在的两个独立的功能和它我的问题不工作我更新的代码我现在累了 – Darlyn
@trolkura,因为你在删除类中的错误部分,把'.add('remove')'调用放在addEventListener调用后面,就像我的代码示例 –