John Lacket
John Lacket

Reputation: 11

After I changed ID Javascript, not working next "click" event, what is the problem?

let x = ["1", "3", "5"]

$("#button").click(
  function num() {
    $("#answers").html(x[0])
    document.getElementById("button").setAttribute("id", "button2");
  }
)

$("#button2").click(
  function num2() {
    $("#answers").html(x[1])
    document.getElementById("button").setAttribute("id", "button3");
  }
)

$("#button3").click(
  function num3() {
    $("#answers").html(x[2])
  }
)

Upvotes: 1

Views: 134

Answers (2)

trincot
trincot

Reputation: 350725

When you have this:

$("#button2").click(.......

... that will look at #button2 right now, not at some future renaming. Since at the start there is no such id, this .click method is not doing anything.

You can achieve this with event delegation, but in your case I would go for a different solution.

Changing the id attribute of a DOM element is really bad practice. Instead use a variable which will determine in which "case" you are, and just use one click handler where you inspect that variable. Something like this:

var state = 1;

$("#button").click(function num() {
    if (state == 1) {
        $("#answers").html(x[0]);
        state = 2; // move to the next state..
    } else if (state == 2) {
        // do something else...
        state = 3;
    } else if (state == 3) {
        // ... etc ...
    }
})

If the logic is really so simple that you want to just display the next entry in the x array, then let the state be that index:

var index = 0;

$("#button").click(function num() {
    $("#answers").html(x[index]);
    index = (index+1) % x.length;  // round robin selection of array value
})

Upvotes: 3

Denis Stukalov
Denis Stukalov

Reputation: 1242

Just add current index and your code will be simple:

let x = ["1","3","5"]
let currentIndex = -1

$("#button").click(() => {
    currentIndex += 1
    $("#answers").html(x[currentIndex])
  }
)

See in playground: https://jsfiddle.net/denisstukalov/x0sq6fry/6/

Upvotes: 0

Related Questions