未捕获的语法错误:意外的标记 ‘function’

huangapple go评论133阅读模式
英文:

Uncaught SyntaxError: Unexpected token 'function'

问题

我看到很多类似的问题,但似乎没有一个能帮助我解决问题。
我得到这个错误 Uncaught SyntaxError: Unexpected token 'function' recipes: 163,指向我的函数 startTimer(),请参见下面的代码。

我看不出我的函数有什么问题,也不知道还能在哪里找了,我已经尝试了一切。

我希望我的 img 标签每 3 秒更改一次 src,就像在我的 ASP.NET MVC 项目中使用 js 的幻灯片一样。


<details>
<summary>英文:</summary>

I&#39;ve seen many questions like this but none seem to be helping me with my issue.
I get this error `Uncaught SyntaxError: Unexpected token &#39;function&#39; recipes: 163` which is pointing on my function startTimer(), see code below.

I dont see anything wrong with my function and I don&#39;t know where to look anymore, I&#39;ve tried everything.

I want my img tag to change src every 3 second, just like a slideshow using js in my ASP.NET MVC project.


<div id="image-slideshow" onload="startTimer()">
<img id="image-changer" src="@Model[0].Image" />
</div>
@section Scripts{
<script>
var index = 0;
var images = [];

    images[0] = @Model[0].Image;
    images[1] = @Model[1].Image;
    images[2] = @Model[2].Image;
    images[3] = @Model[3].Image;
    images[4] = @Model[4].Image;

    function changePic() {
        document.getElementById(&quot;image-changer&quot;).src = images[index];
        console.log(index);
        index &gt; 4 ? index = 0 : index++;
    }

    function startTimer() {
        setInterval(changePic(), 3000);
    }
&lt;/script&gt;

}



I&#39;ve tried to pinpoint what this unexpected error means but I cannot see any problems with the function.

</details>


# 答案1
**得分**: 1

在JavaScript中,[三元运算符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)期望的是表达式,而不是语句。

`index = 0` 是一个语句。

因此,如果你想要有条件地赋值给 `index`,你有两种选项:

### 使用三元运算符进行赋值

```javascript
index = index > 4 ? 0 : index + 1;

这样做是因为0是一个表达式,index + 1也是一个表达式。

使用if进行赋值

if (index > 4) {
    index = 0;
} else {
    index++;
}
英文:

In JavaScript, the ternary operator expects expressions, not statements.

index = 0 is a statement.

So if you want to conditionally assign index, you have 2 options:

Assign using ternary

index = index &gt; 4 ? 0 : index + 1;

This works because 0 is an expression and index + 1 is an expression.

Assign using if

if (index &gt; 4) {
    index = 0;
} else {
    index++;
}

huangapple
  • 本文由 发表于 2023年3月7日 01:35:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定