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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

You'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