简体   繁体   English

意外的令牌,不明白为什么

[英]Unexpected token, can't understand why

I'm new to JS and trying to creating a simple function, I get an error我是 JS 新手并尝试创建一个简单的 function,但出现错误

Uncaught SyntaxError: Unexpected token '{'

Which I do understand, but I can't understand why.我明白,但我不明白为什么。 According to the console, I have a problem in here:根据控制台,我在这里有一个问题:

function displayGallery(galleryName) { 

let src = './Images/' + galleryName + '/';
let imageIndex = 1;
let myGridCells = $('.foodImage');

foreach (image in myGridCells) { <--- problem here.
    let newSrc = src + imageIndex + '.jpg';
    image.attr('src', newSrc);
    imageIndex++;
}

fadeMainGrid();
}

But nothing seems to ne missing or extra '{', what is happening here?但似乎什么都没有丢失或额外的'{',这里发生了什么? I tried but couldn't find an answer to why this is happening.我试过但找不到为什么会发生这种情况的答案。

function displayGallery(galleryName) { 

let src = './Images/' + galleryName + '/';
let imageIndex = 1;
let myGridCells = $('.foodImage');

for (image in myGridCells) { <--- problem SOLVED here.
    let newSrc = src + imageIndex + '.jpg';
    image.attr('src', newSrc);
    imageIndex++;
}

fadeMainGrid();
}

Its for not forEach when looping like this.像这样循环时它不是 forEach 。

see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration见这里: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

To iterate over a jQuery collection use .each :要遍历 jQuery 集合,请使用.each

images.each(function(i, image) {
    let newSrc = src + (i+1) + '.jpg';
    $(image).attr('src', newSrc);
});

it seems to be just a simple syntax error, you can replace "foreach" with "for" and it should work the same这似乎只是一个简单的语法错误,您可以将“foreach”替换为“for”,它应该可以正常工作

instead of being this:而不是这样:

foreach (image in myGridCells) {
    let newSrc = src + imageIndex + '.jpg';
    image.attr('src', newSrc);
    imageIndex++;
}

it should instead be this:它应该是这样的:

for (image in myGridCells) {
    let newSrc = src + imageIndex + '.jpg';
    image.attr('src', newSrc);
    imageIndex++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM