繁体   English   中英

JavaScript中的事件监听器,而不是jQuery

[英]Event Listener in JavaScript not jQuery

$('ul.mylist').on('click', 'li', function(){})

我想将这条jQuery行转换为香草,但我该怎么做呢? 我看着jQuery源,但我很困惑。 是否有简单的方法可以在纯Javascript中执行此操作?

这里的某些功能取决于浏览器,但这基本上就是它的运行方式...

// select all UL elements with the `mylist` class
var uls = document.querySelectorAll('ul.mylist');

// Iterate the collection, and bind the `click` handler
for (var i = 0; i < uls.length; i++)
    uls[i].addEventListener('click', handler, false);

// The `click` handler iterates starting with `event.target` through its
//   ancestors until the bound element is found. Each element matching the
//   "LI" nodeName will run your code.
function handler(event) {
    var node = event.target;
    do {
        if (node.nodeName === "LI") {
            // RUN YOUR CODE HERE
        }
    } while (node !== this && (node = node.parentNode));
}

您可以使用node.matchesSelector(".my.selector")来使选择器测试更加广泛,尽管该方法是在某些浏览器中使用特定于浏览器的属性标志实现的,因此您需要先在Element.prototype上公开它Element.prototype以适当的名称Element.prototype

您可以将点击侦听器绑定到任何元素,如下所示:

<ul id="mylist">
<li> item 1</li>
<li> item 2</li>
<li> item 3</li>
<li> item 4</li>
</ul>

<script type="text/javascript">
function click_handler(){
    alert('you clicked a list');
}
var list=document.getElementById("mylist");
list.onclick=click_handler;

</script>

这是JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM