Home > OS >  how can i pass a dynamic argument to a EventListener?
how can i pass a dynamic argument to a EventListener?

Time:06-15

have this code:

   function roleDescription() {
    // вторая ступень = описание роли при наведении, выбор роли при клике
    for (let i = 0; i < originDescription.length; i  ) {
      buttons[i].addEventListener('mouseover', asignDesc);
      buttons[i].addEventListener('click', asignRole, {
        once: true
      });
    }
  }

and this functions:

    function asignRole(i) {
    playerrole = role[i];
    alert(playerrole);
    makeSpecial();
  }

  function asignDesc(i) {
    maintext.textContent = originDescription[i];
    maintext.style.fontSize = '15px';
  }

how can i pass [i] from cycle [for] so i can get all this scipt goin' well?

CodePudding user response:

You can use bind

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i  ) {
  buttons[i].addEventListener('click', asignRole.bind(buttons[i], i), {
    once: true
  });
}


function asignRole(i) {
  console.log(i);
}
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>

You can use a function

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i  ) {
  buttons[i].addEventListener('click', () => asignRole(i), {
    once: true
  });
}


function asignRole(i) {
  console.log(i);
}
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>

You can use data attributes

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i  ) {
  buttons[i].addEventListener('click', asignRole, {
    once: true
  });
}


function asignRole(evt) {
  console.log(evt.currentTarget.dataset.id);
}
<button type="button" data-id="0">0</button>
<button type="button" data-id="1">1</button>
<button type="button" data-id="2">2</button>

  • Related