Переопределить переменную в функции для определенной части - PullRequest
1 голос
/ 21 ноября 2019

У меня есть следующий код:

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>

Спасибо!

1 Ответ

1 голос
/ 21 ноября 2019

Вам необходимо использовать обратные вызовы для задержки каждого fadeIn / fadeOut до завершения предыдущего.

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, function() {
    window.scrollBy(0, 200);
    $("#btext").fadeOut(2000, function() {
      $("#btext").html(a).fadeIn(2000, function() {
        a = 'Happy birthday to you, ' + $name;
        $("#btext").fadeOut(2000, function() {
          $("#btext").html(a).fadeIn(2000);
        });
      });
    });
  });
}
<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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...