search

Home  >  Q&A  >  body text

javascript - js event delegation, how do the child elements of e.target trigger events?

When clicking the td in the table, the data bound to the td is fed back.

<p class='wrapper'>
    <table>
        <thead>.......</thead>
        <tbody>
            <tr>
                <td data-data='1'>1</td>
                ....
                <td data-data='2'><font color='red'>2</font></td>
                ....
            </tr>
            ....
        </tbody>
    </table>
</p>

The table is dynamically generated. Bind the event to the wrapper and use the target to trigger the tag td. Because some tds have the sub-element font inside, the area where the font element is clicked cannot be triggered.

$wrapper = document.querySelector('.wrapper');
$wrapper.addEventListener('click', function(e){
    if(e.target.tagName.toLowerCase === 'td') {
        console.log(e.target.dataset.data);
    }
},false);
黄舟黄舟2756 days ago493

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:28:36

    $wrapper = document.querySelector('.wrapper');
    $wrapper.addEventListener('click', function(e) {
      for (var el = e.target; el !== e.currentTarget; el = el.parentElement) {
        if(el.tagName.toLowerCase() === 'td') {
            return console.log(el.dataset.data);
        }
      }
    }, false);

    reply
    0
  • Cancelreply