我正在循环一个包含多个元素的对象,每个元素都包含多个媒体查询。
在循环中,我动态调用 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
. 我如何保持x
和y
等于未来match
es 最初传递的内容?