2017-09-25 70 views
1

我試圖做到以下幾點:爲什麼text()函數執行之前淡出()函數

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

的可能的複製[調用以前的功能後的功能是完整](https://stackoverflow.com/questions/5000415/call-a-function-after-previous-function-is-complete) –

回答

4

由於衰落是一個異步操作。

做你做什麼,請使用hide回調:

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

在評論你說:

好,我都嘗試過,但在原始代碼有一個循環和功能只在循環結束時工作

回調將有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"); 
     }); 
    } 
}); 
+0

好吧,我已經嘗試過,但在原始代碼中有一個循環和功能的工作只在循環結束時... –

+0

@ S.josh:那麼你會想使用'this';我已經添加到答案。 –

+0

再次看帖子,它沒有工作 –

相關問題