我想创建一个辅助函数来帮助迭代子节点。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
NodeList.prototype.addEvent = func => {
for (let i = 0; i < this.length; i++) {
this[i].addEventListener('click', func)
}
}
let myList = document.getElementsByClassName('list')[0]
function test() {
console.log('Hello')
}
myList.addEvent(test)
</script>
</body>
</html>
无论我尝试什么,我都会得到“myList.addEvent不是函数”。
我看过一个如何在MDN(页面中间)上实现这一点的示例,来源:https://developer.mozilla.org/en-US/docs/Web/API/NodeList
var elements = document.querySelectorAll(".suggestions");
NodeList.prototype.addEventListener = function(event, func) {
this.forEach(function(content, item) {
content.addEventListener(event, func);
});
}
function log() {
console.log(this, " was clicked");
}
elements.addEventListener("click", log);
更新:
使用.querySelectorAll()可以将原型添加到NodeList,但不能用于.getElementsByClassName(...)[0] ,. getElementsByTagName(...)[0]或.getElementById(...) - 有谁知道为什么这只适用于静态节点列表?
答案 0 :(得分:1)
您正在创建AddEvent()
,但是正在调用addEvent()
- 请注意案例中的差异。
答案 1 :(得分:0)
代码存在多个问题。
NodeList.prototype.AddEvent = function( func ) {
for (let i = 0; i < this.length; i++) {
this[i].addEventListener('click', func); //notice this[i] instead of this
}
}
var myList = document.querySelectorAll('.list'); //notice that element name is not .list so use querySelectorAll
myList.AddEvent(test); //addEvent to AddEvent
function test()
{
console.log('Hello')
}
<div class="list">
List div
</div>