HTML:
<form class="hotels-filters">
<div role="radio" aria-checked="false" tabindex="1" id="all" class="hotel-filter hotel-filter-reset hotel-filter-active">Reset filters</div>
<div role="radio" aria-checked="false" tabindex="1" id="expensive-first" class="hotel-filter hotel-filter-dropdown">Expensive first</div>
<div role="radio" aria-checked="false" tabindex="1" id="stars" class="hotel-filter hotel-filter-dropdown">Start from 2</div>
<div role="radio" aria-checked="false" tabindex="1" id="min-rating" class="hotel-filter hotel-filter-dropdown">Not under 6</div>
<div role="radio" aria-checked="false" tabindex="1" id="distance" class="hotel-filter hotel-filter-dropdown">Close to me</div>
<div role="radio" aria-checked="false" tabindex="1" id="favorites" class="hotel-filter">Favorites</div>
</form>
JS:
var filters = document.querySelectorAll('.hotel-filter');
for (var i = 0; i <= filters.length; i++) {
filters[i].onclick = function(evt) {
var clickedElementID = evt.target.id;
setActiveFilter(clickedElementID);
};
}
浏览器突出显示这部分代码
= function(evt) {
并且说“未捕获TypeError:无法设置属性'onclick'未定义”
答案 0 :(得分:3)
你需要更新for循环条件,否则,在最后一次迭代它将是undefined
,因为索引超出范围(最大索引是filters.length - 1
,最后一个索引是{{1 }})。错误是抛出,因为在最后一次迭代中,您尝试在filters.length
上设置onclick
属性,这是不可能的。
undefined
答案 1 :(得分:0)
迭代器的元素数量超过了一个数字。这是正确的迭代 var filters = document.querySelectorAll('。hotel-filter');
for (var i=0; i < filters.length; i++) {
filters[i].onclick = function(evt) {
var clickedElementID = evt.target.id;
setActiveFilter(clickedElementID);
};
}