![](/img/trans.png)
[英]Why assign a variable to an anonymous function and redefine it again in that function?
[英]Redefine Variable in Function For a Certain Part
我有以下代碼:
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>
謝謝!
$("#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>
您需要使用回調來延遲每個淡入/淡出,直到前一個完成。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.