-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[js] 第97天 写例子说明如何给li绑定事件(ul下有1000+个li)? #969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
使用jq |
在不考虑任何情况时,直接使用 当子元素过多时,可以利用“事件冒泡”在 document.getElementsByTag('ul')[0].addEventListener('event', (e) => {
// 利用 e.target 对冒泡上来的元素做区分
// e.target.nodeName, e.target.id 等
}) |
首选事件代理 <ul>
<li>1111111111111</li>
<li>2222222222222</li>
<li>3333333333333</li>
<p>44444444444</p>
</ul>
<script>
document.querySelector('ul').addEventListener('click', function (e) {
if (e.target.tagName === 'LI') {
// ...
}
})
</script> |
用事件委托直接将事件绑定在父元素上,通过 |
稍微优化一点点
|
|
采用事件委托,加switch-case是为了处理不同子元素的事件。 `<ul> <li id='1'>1</li> <li id='2'>2</li> <li id='3'>3</li> </ul> <script> $('ul').click(function(e) { switch(e.target.id){ case '1': console.log(1) break; case '2': console.log(2) break; default: console.log('default') } }) </script>` |
这题明显考的是事件委托,利用事件冒泡的原理把事件绑定到父元素,在父元素识别是哪个子元素触发。 |
难道不toUpcase下吗? 把e.target.tagName 变成大写? |
|
事件委托: ul.addEventListener('click', function(e) { |
第97天 写例子说明如何给li绑定事件(ul下有1000+个li)?
The text was updated successfully, but these errors were encountered: