Skip to content
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

[js]事件委托考察 #17

Open
f2ebill opened this issue Jan 16, 2016 · 2 comments
Open

[js]事件委托考察 #17

f2ebill opened this issue Jan 16, 2016 · 2 comments

Comments

@f2ebill
Copy link
Member

f2ebill commented Jan 16, 2016

<ul>
  <li class='target'>
      <span>test</span>
 </li>
</ul>
  • 点击classtargetli可以 alert 出其所含内容(如上方代码点击弹出“test”)
  • ul动态新增li元素的情况下,也要有相同效果
  • 使用原生js实现,不使用jQuery
@VaJoy VaJoy changed the title [js]在事件委托,让委托元素的后代元素也响应事件 [js]事件委托考察 Jan 16, 2016
@VaJoy
Copy link
Member

VaJoy commented Jan 17, 2016

挽尊

    var ul = document.querySelector('ul');
    ul.addEventListener('click', function (e) {
        var target = e.target,
            f = function (t) { console.log(t);
                var className = t.className;
                if (t.tagName === 'LI' && className && className.indexOf('target') >= 0) {
                    alert(t.innerHTML)
                } else if(t != ul) {
                    f(t.parentNode)
                }
            };
        f(target)
    }, false)

@xifengxx
Copy link

`var ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
var target = e.target;
(function(i){
var cln=i.className?i.className:' ';
if(i.tagName==="LI" &&cln.indexOf('target')>=0){
alert(i.innerHTML);
}
})(target);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants