我正在学习香草JavaScript并在这里使用事件委托。 我在控制台上收到“ TypeError-无法读取null的addeventlistener的属性”消息,并且功能变量显示该变量未被使用。
var setupEventListener = function (){
document.querySelector(DOM.container).addEventListener('click',
ctrlDeleteItem ); /*this is the line which shows the error*/
};
var ctrlDeleteItem = function(event) {
console.log(event.target);
};
DOM.container是包含属性的对象,这些属性表示HTML中JS中使用的类。 例如此处-var DOM = {container:'.container clearfix'};
这是项目的HTML部分-
<div class="container clearfix"> /*this class is selected for the event delegation*/
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
答案 0 :(得分:1)
.container clearfix
不是有效的选择器。它应该是.container.clearfix
。请在更新后查看您的示例。
var DOM = {
container: '.container.clearfix'
};
var setupEventListener = function() {
document.querySelector(DOM.container).addEventListener('click',
ctrlDeleteItem); /*this is the line which shows the error*/
};
var ctrlDeleteItem = function(event) {
console.log(event.target);
};
setupEventListener();
<div class="container clearfix"> /*this class is selected for the event delegation*/
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
</div>
</div>
</div>