1

This code below works fine when i put a number after my eq.

 for (i=0; i<$("button.mark").length ; i++){

   $("button.mark:eq(0)").on("click", e => {
     e.preventDefault()
     e.stopPropagation()
     $("div.popup:eq(0)").show()
  
      if ($("div.popup:eq(0)").css("display") === "block") {
        $(window).on("click", () => {
          $("div.popup:eq(0)").hide()
        })
      }
   })
 }

but it stop working when i try to put it in the for with i. Do you know why ?

for (i=0; i<$("button.mark").length ; i++){

   $("button.mark:eq(i)").on("click", e => {
     e.preventDefault()
     e.stopPropagation()
     $("div.popup:eq(i)").show()
  
      if ($("div.popup:eq(i)").css("display") === "block") {
        $(window).on("click", () => {
          $("div.popup:eq(i)").hide()
        })
      }
   })
 }
8uld0zr
  • 69
  • 1
  • 7
  • 3
    just change this `$("button.mark:eq(i)")` to `$("button.mark:eq("+i+")")` and `$("div.popup:eq("+i+")")` – Swati Apr 26 '21 at 13:05
  • 3
    Also related [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – charlietfl Apr 26 '21 at 13:10
  • See also [How to interpolate variables in strings in JavaScript, without concatenation?](https://stackoverflow.com/q/3304014/215552). – Heretic Monkey Apr 26 '21 at 13:33

1 Answers1

0

here you are the answer thanks to @swati and @charlie

for (let i=0; i<$("button.mark").length ; i++){

  $("button.mark:eq("+i+")").on("click", e => {
    e.preventDefault()
    e.stopPropagation()
    $("div.popup:eq("+i+")").show()
 
      if ($("div.popup:eq("+i+")").css("display") === "block") {
        $(window).on("click", () => {
          $("div.popup:eq("+i+")").hide()
        })
      }
  })
}

I have added ("+i+") and "let" in the for loop condition !

8uld0zr
  • 69
  • 1
  • 7