H
H
Hellas2017-08-29 01:11:06
JavaScript
Hellas, 2017-08-29 01:11:06

How to bind an event to each element in a list?

For example:

<ul>
  <li name="one">1</li>
  <li name="two">2</li>
  <li name="three">3</li>
  <li name="four">4</li>
  <li name="five">5</li>
  <li name="six">6</li>
</ul>

Each element limust be written -
onMouseOver={() => this.hover(event.target.getAttribute('name'))}
  onMouseOut={() => this.hover(false)}

There are a lot of elements, is it possible to specify these events without assigning them to each element?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nicholas, 2017-08-29
@healqq

delegation only if.

P
PAJCH, 2017-08-29
@PAJCH

It's OK. Only visually it seems that we are hanging an event on each element. In fact, React is much smarter. He delegates them himself.

P
Pavel Kornilov, 2017-08-29
@KorniloFF

<ul onclick= "fn(event)">
  <li name="one">1</li>
  <li name="two">2</li>
  <li name="three">3</li>
  <li name="four">4</li>
  <li name="five">5</li>
  <li name="six">6</li>
</ul>
<script>
function fn (e) {
  alert(e.target.textContent);
  e.stopPropagation();
}
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question