admin管理员组文章数量:1323714
I have a small slider in my website and it always worked perfectly but now I get this error:
Syntax error: "myIndex" is read-only
This is my JavaScript code:
const myIndex = 0;
carousel();
function carousel() {
let i;
const x = document.getElementsByClassName(`slides`);
for (i = 0;i < x.length;i ++) {
x[i].style.display = `none`;
}
myIndex ++;
if (myIndex > x.length) {
myIndex = 1;
}
x[myIndex - 1].style.display = `block`;
setTimeout(carousel, 4000); // Change image every 2 seconds
}
And this is the html:
<div class="home-slider">
<img class="slides" src="assets/img/slide_1.jpg" alt="slide1">
<img class="slides" src="assets/img/slide_2.jpg" alt="slide2">
<img class="slides" src="assets/img/slide_3.jpg" alt="slide3">
</div>
How can I fix this?
I have a small slider in my website and it always worked perfectly but now I get this error:
Syntax error: "myIndex" is read-only
This is my JavaScript code:
const myIndex = 0;
carousel();
function carousel() {
let i;
const x = document.getElementsByClassName(`slides`);
for (i = 0;i < x.length;i ++) {
x[i].style.display = `none`;
}
myIndex ++;
if (myIndex > x.length) {
myIndex = 1;
}
x[myIndex - 1].style.display = `block`;
setTimeout(carousel, 4000); // Change image every 2 seconds
}
And this is the html:
<div class="home-slider">
<img class="slides" src="assets/img/slide_1.jpg" alt="slide1">
<img class="slides" src="assets/img/slide_2.jpg" alt="slide2">
<img class="slides" src="assets/img/slide_3.jpg" alt="slide3">
</div>
How can I fix this?
Share Improve this question edited Mar 27, 2017 at 14:42 James Donnelly 129k35 gold badges214 silver badges223 bronze badges asked Mar 27, 2017 at 14:38 JoyceEmmaJoyceEmma 271 silver badge2 bronze badges1 Answer
Reset to default 7You're defining myIndex
with the const
statement. const
creates a constant; that is to say a value which cannot be changed after first being initialised.
The error is being thrown when executing myIndex ++
, which attempts to increment the stored value.
Instead of const
, use let
or var
:
let myIndex = 0;
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.
– MDN's
const
Documentation
本文标签: javascriptWhy do I have a readonly error in my slideshowStack Overflow
版权声明:本文标题:javascript - Why do I have a read-only error in my slideshow? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742126347a2421960.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论