gpt4 book ai didi

javascript - enquire.js - 如何在动态创建的寄存器函数中维护变量?

转载 作者:行者123 更新时间:2023-11-30 17:38:40 25 4
gpt4 key购买 nike

我正在遍历一个包含多个元素的对象,每个元素都包含多个媒体查询。

在循环中,我动态调用 enquire.js .register() 来对比赛执行某些操作。这最初有效,但在循环之外,并且在调整浏览器大小时,匹配不再有效,因为循环中使用的变量已递增到循环中的最高值。

用代码解释可能更容易!

这是 images 对象:

var images = [
{
"selector":"[data-id=\"0\"]",
"breakpoints":[
{
"mediaquery":"(max-width: 31.25em) ",
"src":"image-0-small.jpg"
},
{
"mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
"src":"image-0-medium.jpg"
},
{
"mediaquery":"(min-width: 46.3125em) ",
"src":"image-0-large.jpg"
}
]
},
{
"selector":"[data-id=\"1\"]",
"breakpoints":[
{
"mediaquery":"(max-width: 31.25em) ",
"src":"image-1-small.jpg"
},
{
"mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
"src":"image-1-medium.jpg"
},
{
"mediaquery":"(min-width: 46.3125em) ",
"src":"image-1-large.jpg"
}
]
},
{
"selector":"[data-id=\"2\"]",
"breakpoints":[
{
"mediaquery":"(max-width: 31.25em) ",
"src":"image-2-small.jpg"
},
{
"mediaquery":"(min-width: 31.3125em) and (max-width: 46.25em) ",
"src":"image-2-medium.jpg"
},
{
"mediaquery":"(min-width: 46.3125em) ",
"src":"image-2-large.jpg"
}
]
}
];

这是循环:

for (var x=0; x < images.length; x++) {
for (var y=0; y < images[x]['breakpoints'].length; y++) {
enquire.register(images[x]['breakpoints'][y]['mediaquery'], function () {
// x and y unfortuntaley equal 3 & 3 after the loop, so how do I maintain them from inside the match?
// Interestingly, Firefox doesn't seem attempt to fire matches more than once. Chrome and IE 11 do, which is where I found the error that images[x] is undefined

console.log('match-index', x, y);
console.log('match-images', images);
console.log('match-mediaquery', images[x]['breakpoints'][y]['mediaquery']);
});
}
}

images[x] 未定义,因为 x = 3。我如何让 xy 等于在未来的 matches 中最初传入的值?

最佳答案

变量范围在函数级别维护。因此,您必须找到一种方法来在每次迭代时创建变量的副本,并将该副本传递给注册函数。

一种方法是创建一个立即执行的函数表达式,该表达式返回最终将由 register() 执行的函数。

它看起来像这样:

(function(innerX, innerY) {
return function() {
// use innerX and innerY here
};
}(x, y))

它的工作方式是立即执行的函数表达式为其返回的函数创建一个闭包,它引用了 x 和 y 副本 - innerX 和 innerY。

关于javascript - enquire.js - 如何在动态创建的寄存器函数中维护变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com