[英]Can't figure out why the loop is not working
I know that there are countless questions about for loops or equivalent in JavaScript but I can't figure out how to make this one work.我知道在 JavaScript 中有无数关于 for 循环或等效项的问题,但我不知道如何使这个工作。
<!-- Comes from https://github.com/sindresorhus/screenfull.js/edit/master/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/screenfull.js/5.0.2/screenfull.min.js"></script>
</head>
<body>
<img id = "img1" src="https://placeimg.com/200/150/nature" alt="">
<img id = "img2" src="https://placeimg.com/200/150/nature/2" alt="">
<button id="test">Click</button>
<script>
// WORKS:
// $(function () {
// $('#img1').click(function () {
// screenfull.request($('#img1')[0]);
// });
// });
var ids = ["#img1", "#img2", "#test"];
var item;
for (item of ids) {
$(function () {
$(item).click(function()) {
screenfull.request($(item)[0]);
}
})
}
</script>
</body>
</html>
Expected output: clicking on either of the two images should put it fullscreen.预期 output:单击两个图像中的任何一个都应将其全屏显示。 Any idea?
任何想法? (I started with a for loop but I accept other solutions.)
(我从 for 循环开始,但我接受其他解决方案。)
I won't know the number of items in advance (nor their names) so the solution has to work with this specificity.我不会提前知道项目的数量(也不会知道它们的名称),因此解决方案必须适用于这种特殊性。
Just make a selector with both ids只需制作一个具有两个 id 的选择器
$('#img1, #img2').click(function () {
screenfull.request(this);
});
with an array有一个数组
var imgs = ['#img1', '#img2'];
$(imgs.join(',')).click(function () {
screenfull.request(this);
});
if you want to loop and reinvent what jQuery does for you如果您想循环并重新发明 jQuery 为您做的事情
var imgs = ['#img1', '#img2'];
imgs.forEach(function(id){
$(id).click(function () {
screenfull.request(this);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.