我正在尝试执行以下操作:
- 淡出一个
div
- 更改其文本
- 再次淡入
问题是,第 2 步发生在第 1 步之前。为什么会这样?
代码如下:
<p id="p">
hi!
</p>
<button onclick="foo()">
wefew
</button>
<script>
$("button").click(function (){
var item = $("#p");
item.hide("slow");
item.text("text");
item.show("slow");
})
</script>
https://jsfiddle.net/pq35yd5t/ 编辑: 我发现问题是我正在使用 for 循环并且回调函数仅适用于 ht elast 循环......为什么,又一次 代码:
for (var i = 0; i < ob_prop.length; i++) {
if (ob_prop[i]=="tag") {
continue;
}
var item = $("#"+ob_prop[i]);
item.hide("slow", function() {
item.text(work[pointer][ob_prop[i]]).show("slow");
});
}
最佳答案
因为淡化是一个异步操作。
要完成您正在做的事情,请使用 hide
上的回调:
$("button").click(function (){
var item = $("#p");
item.hide("slow", function() {
item.text("text");
item.show("slow");
});
})
在您的评论中:
ok i have tried it but in the original code there's a for loop and function work only at the end of the loop
回调会将 this
设置为与回调相关的元素,因此使用那个而不是 item
:
$("button").click(function (){
var item = $("#p");
item.hide("slow", function() {
$(this).text("text").show("slow");
});
})
您的最新 编辑存在循环闭包问题。有关详细信息,请参阅该问题的答案,但解决方案之一是使用 $.each
(或 Array.prototype.forEach
如果您不必担心过时的浏览器像 IE8):
$.each(function(index, ob) {
if (ob != "tag") {
$(ob).hide("slow", function() {
$(this).text(work[pointer][ob]).show("slow");
});
}
});
关于javascript - 为什么 jquery 中的 text() 函数在 fadeOut() 函数之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409253/