【问题标题】:why text() function in jquery execute before fadeOut() function为什么jQuery中的text()函数在fadeOut()函数之前执行
【发布时间】:2017-09-26 01:17:51
【问题描述】:

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

  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");
        });
    }

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

因为淡入淡出是一个异步操作。

要执行您正在执行的操作,请使用hide 上的回调:

$("button").click(function (){
    var item = $("#p");
    item.hide("slow", function() {
        item.text("text");
        item.show("slow");
    });
})

在你说过的评论中:

好的,我已经尝试过了,但是在原始代码中,有一个 for 循环,并且函数仅在循环结束时起作用

回调会将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");
        });
    }
});

【讨论】:

  • 好的,我已经尝试过了,但是在原始代码中有一个 for 循环,并且函数只在循环结束时工作......
  • @S.josh:那么你会想要使用this;我已经添加到答案中。
  • @S.josh:那是closures in loops problem,与您的原始代码无关(但有时会在您执行 MCVE 时发生,不用担心)。那里的答案应该解决这方面的问题。我在上面的末尾添加了一个选项。
猜你喜欢
  • 2013-07-01
  • 2018-08-12
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 2013-11-05
  • 1970-01-01
相关资源
最近更新 更多