javascript - js event delegation, how do the child elements of e.target trigger events?
黄舟
黄舟 2017-05-19 10:26:36
0
1
486

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);
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
伊谢尔伦
$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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template