JavaScript addEventListener函数上未定义事件对象
我正在尝试根据JavaScript addEventListener函数上未定义事件对象,javascript,html,Javascript,Html,我正在尝试根据HTML选择,使用以下代码进行切换选择: document.getElementById("filterList").addEventListener("change", function(evt) { switch(evt.options[evt.selectedIndex].value) { case "priceAsc": sortAndShow
HTML
选择,使用以下代码进行切换
选择:
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;
}
});
和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>
塞莱克奥尼过滤。。。
阿森森特公园
下缘
名称(A-Z)
名义(Z-A)
但当我选择and选项时,控制台中会显示以下消息:
Uncaught TypeError: can't access property "undefined", evt.options is undefined
<anonymous> http://192.168.1.115/proyectojap/js/products.js:95
未捕获类型错误:无法访问属性“未定义”,evt.options未定义
http://192.168.1.115/proyectojap/js/products.js:95
您需要在evt.target.options
和evt.target.selectedIndex
上使用,以获取所选的选项
值。此外,还可以使用as来获得相同的结果
另外,您可以在一个选项中使用两个值属性not。在上一个选项中有两个值
现场演示:
document.getElementById(“过滤器列表”).addEventListener(“更改”,函数(evt){
console.log(evt.target.options[evt.target.selectedIndex].value)
/*开关(evt.target.options[evt.target.selectedIndex].value){
案例“priceAsc”:
sortAndShowProducts(按价格、currentProductsArray订购);
打破
案例“priceDesc”:
sortAndShowProducts(订单按价格说明,当前产品阵列);
打破
案例“nameAsc”:
sortAndShowProducts(按名称订购ASC,当前产品阵列);
打破
案例“priceAsc”:
sortAndShowProducts(订单名称、当前产品名称);
打破
违约:
log(“Selección inválida:+evt.options[evt.selectedIndex].value”);
打破
} */
});代码>
塞莱克奥尼过滤。。。
阿森森特公园
下缘
名称(A-Z)
名义(Z-A)
这不是问题所在,但是-您不应该在一个选项中包含两个值。或者这是一个输入错误?在evt
和options
之间添加target
,就像这样evt.target.options
。这两个值是错误的。谢谢@AlwaysHelping,你解决了我的问题!