[英]Event object is undefined on JavaScript addEventListener function
I'm trying to make a switch
selection based on an HTML
select with the following code:我正在尝试使用以下代码基于
HTML
选择进行switch
选择:
document.getElementById("filterList").addEventListener("change", function(evt) {
switch(evt.options[evt.selectedIndex].value) {
case "priceAsc":
sortAndShowProducts(ORDER_ASC_BY_PRICE, currentProductsArray);
break;
case "priceDesc":
sortAndShowProducts(ORDER_DESC_BY_PRICE, currentProductsArray);
break;
case "nameAsc":
sortAndShowProducts(ORDER_ASC_BY_NAME, currentProductsArray);
break;
case "priceAsc":
sortAndShowProducts(ORDER_DESC_BY_NAME, currentProductsArray);
break;
default:
console.log("Selección inválida: " + evt.options[evt.selectedIndex].value);
break;
}
});
And the HTML tag:和 HTML 标签:
<select name="selectFilter" id="filterList" class="browser-default custom-select">
<option value="" disabled selected>Seleccione el filtro...</option>
<option value="priceAsc">Precio ascendente</option>
<option value="priceDesc">Precio descendente</option>
<option value="nameAsc">Nombre(A-Z)</option>
<option value="priceAsc" value="nameDesc">Nombre(Z-A)</option>
</select>
But when I select and option, I get the following message in console:但是当我选择和选项时,我在控制台中收到以下消息:
Uncaught TypeError: can't access property "undefined", evt.options is undefined
<anonymous> http://192.168.1.115/proyectojap/js/products.js:95
You need to use Event.target on both evt.target.options
and evt.target.selectedIndex
to get the selected option
value.您需要使用Event.target两个
evt.target.options
和evt.target.selectedIndex
获得所选择的option
值。 In addition, you can also use currentTarget as well to have the same results此外,您还可以使用currentTarget来获得相同的结果
Also, you can not have two value attributes
in one option.此外,一个选项中不能有两个值
attributes
。 You had two
values in your last option
.您的最后一个
option
有two
值。
Live Demo:现场演示:
document.getElementById("filterList").addEventListener("change", function(evt) { console.log(evt.target.options[evt.target.selectedIndex].value) /* switch (evt.target.options[evt.target.selectedIndex].value) { case "priceAsc": sortAndShowProducts(ORDER_ASC_BY_PRICE, currentProductsArray); break; case "priceDesc": sortAndShowProducts(ORDER_DESC_BY_PRICE, currentProductsArray); break; case "nameAsc": sortAndShowProducts(ORDER_ASC_BY_NAME, currentProductsArray); break; case "priceAsc": sortAndShowProducts(ORDER_DESC_BY_NAME, currentProductsArray); break; default: console.log("Selección inválida: " + evt.options[evt.selectedIndex].value); break; } */ });
<select name="selectFilter" id="filterList" class="browser-default custom-select"> <option value="" disabled selected>Seleccione el filtro...</option> <option value="priceAsc">Precio ascendente</option> <option value="priceDesc">Precio descendente</option> <option value="nameAsc">Nombre(AZ)</option> <option value="priceAsc">Nombre(ZA)</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.