javascript - 为某个部分重新定义函数中的变量
问题描述
我有以下代码:
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>
推荐阅读
- python - Django 自定义中间件执行两次
- ios - 在 iOS 中查找两个日期的差异
- javascript - socket.io 中经过身份验证的房间中的问题
- php - 告诉我为什么我也可以将数组作为对象访问
- windows - 无法登录Window Partner center Dashboard
- backslash - 字符串中的反斜杠给出 ¥ 而不是反斜杠
- typescript-typings - 如何修复此错误 TS2322:类型“元素”不可分配给类型“HTMLLIElement”
- javascript - 在多选下拉列表中,我无法在列表中的空格之后获取所选值
- python-3.x - 损坏的 DAG:没有名为 auth 的模块
- linux - -bash: /usr/local/cpanel/3rdparty/bin/perl: 没有这样的文件或目录 - linux 服务器有点崩溃