首页 > 解决方案 > 为某个部分重新定义函数中的变量

问题描述

我有以下代码:

var $name=prompt("In order for this page to work, we just need a piece of information. Please enter your first name.");
var $age=prompt("Please enter your new age.")

function startSong() {
    var a = 'Happy birthday to you';
    $("#btext").html(a).fadeIn(2000);
    window.scrollBy(0, 200);
    $("#btext").fadeOut(2000);
    $("#btext").html(a).fadeIn(2000);
    a = 'Happy birthday to you, ' + $name;
    $("#btext").fadeOut(2000);
    $("#btext").html(a).fadeIn(2000)

}

我希望它首先打印两次“祝你生日快乐”,然后打印出“祝(姓名)生日快乐”。但是,它似乎直接跳到变量的重新定义。

这是相关的HTML:

<button onclick="startSong()">Now, we all want to sing you Happy Birthday! Go on and click this button!</button>
<h5 id=btext> </h5>

谢谢!

标签: javascriptjquery

解决方案


$("#btext").html(a)调用和分配a不要等待前面的淡入淡出效果完成。所以即使之前设定的效果还没有完成,所有这些陈述都会发生。它们是异步操作

fade* 调用可以传递一个回调,让代码在效果完成后运行。将您的代码放入正确的 fade* 回调中以获得预期的操作:

$("#btext").html(a).fadeIn(2000,function(){
  window.scrollBy(0, 200);
  $("#btext").fadeOut(2000,function(){
    $("#btext").html(a).fadeIn(2000,function(){
      //and so on
    });
  });
});

显然这会导致回调地狱

因此,您也可以在淡入淡出*效果之间排队您的操作:

function startSong() {
  let btext = $("#btext");
  let a = "Happy birthday to you"; 
  let $name = "Stackoverflow";
  btext.html(a)
       //internally adds the effect to the fx queue
       .fadeIn(2000)
       //internally adds the effect to the fx queue
       .fadeOut(2000)
       //adds the code to change the html to fx queue
       //executes when the previous queue item is done
       .queue(function(next) {
         btext.html(a);
         //call next to let the queue advance to the next item
         next();
       })
       .fadeIn(2000)
       .fadeOut(2000)
       .queue(function(next) {
         a = 'Happy birthday to you, ' + $name;
         btext.html(a);
         next();
        })
        .fadeIn(2000);
}
#btext {
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="startSong()">Now, we all want to sing you Happy Birthday! Go on and click this button!</button>
<h5 id=btext> </h5>


推荐阅读