[英]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.