如何将变量发送到异步 jQuery 函数并确保变量之后不会更改?
我有这段代码可以更改字典中每个键的键变量。 目的是用这个键的值更新 html dom。我想要的是在值更新时添加淡入和淡出过渡。问题是,目前,由于 .fadeOut() 函数似乎是异步的,因此在 fadeOut() 完成之前键已更改,因此当我在 fadeOut 之后更改值时,键是其他内容,并且我更新的值是错误的。这是例子!
$(document).ready(function () {
var devices = {};
devices.a = 10;
devices.b = 22;
devices.c = 440;
devices.d = 435;
devices.e = 56475;
devices.h = "dfgfsd";
var fadeTime = 1000;
for (key of Object.keys(devices)) {
console.log(key + " | " + devices[key]);
dom = document.getElementById(key);
if(dom != undefined){
$( dom ).fadeOut( fadeTime, function() {
$( this ).text(devices[key]).fadeIn(fadeTime);
});
}
}
});
https://jsfiddle.net/5zr8ts9f/15/
你可以看到所有字段都得到了更新了字典的最后一个值!
有没有办法分离我们发送到 jQuery 函数的变量?
I have this code that change the key variable for each key in a dict.
The purpose is to update html dom with the value of this key. What i want is to add a fadeIn and fadeOut transition on value update. the problem is that currently, since the .fadeOut() function seems async, the key got changed before the fadeOut() is finised so when i change the value after the fadeOut, the key is something else and the value i update are wrong. here is the exemple!
$(document).ready(function () {
var devices = {};
devices.a = 10;
devices.b = 22;
devices.c = 440;
devices.d = 435;
devices.e = 56475;
devices.h = "dfgfsd";
var fadeTime = 1000;
for (key of Object.keys(devices)) {
console.log(key + " | " + devices[key]);
dom = document.getElementById(key);
if(dom != undefined){
$( dom ).fadeOut( fadeTime, function() {
$( this ).text(devices[key]).fadeIn(fadeTime);
});
}
}
});
https://jsfiddle.net/5zr8ts9f/15/
You can see there that all the field get updated with the last value of the dict!
Is there a way to detach of the variable we send to the jQuery function ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于找到了方法!
I final have found a way to do it!!