请问class不能做事件对象吗?li标签使用class无法触发事件请社区帮帮忙解决一下

我是对JavaScript不太了解,触发事件必须要用id命名的对象才能触发事件吗?


<!doctype html>
<html lang="utf-8">
<head>
<title></title>    
</head>
    
<style>
    ul{
        list-style-type: none;
    }
    li.width{
        margin: 30px auto;
        padding: 30px;
    }
    li.width{
        width: 50px;
        height: 50px;
        color: #000000;
        font-size: 20px;
        line-height: 50px;
        background: #f5f5f5;
    }
    </style>    
<body>
    <ul>
     <li class="width">1111111</li>
    </ul>
</body>
    
<script>
    var Lis = document.getElementsByClassName("width")
Lis.onmouseout = function(){
    this.style.backgroundColor = "#f5f5f5";
    this.style.borderBottom = "1px solid #f5f5f5";
}
Lis.onmouseover = function(){
    this.style.backgroundColor = "#FFF";
    
}
</script>
</html>

通过类名获取元素得到的是对象数组,你改成
var Lis = document.getElementsByClassName("width")[0]应该就可以了

这个Lis获取的是列表,所以你得做个for循环去设置click事件

img