javascript - 为什么 jquery 中的 text() 函数在 fadeOut() 函数之前执行

标签 javascript jquery html

我正在尝试执行以下操作:

  1. 淡出一个div
  2. 更改其文本
  3. 再次淡入

问题是,第 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/

相关文章:

javascript - 使用 PHP 填充 Bootstrap 输入 - 字符串变量中出现空格错误

javascript - 随着内容的增长向下推页脚

javascript - D3.js - 文本未显示在节点中

jQuery 悬停菜单不会消失

javascript - 你可以吗?如果可以,你如何获得默认光标作为图像?

jQuery ready() 直接调用,带有自定义参数

javascript - 使用 Ajax 的大数据表上的下拉过滤器列表

javascript - 动态填充的大型菜单

javascript - Java 中的等效数据结构?

JavaScript函数结构