li 点击时未处理点击事件

Click event not handled on li click

我正在尝试在 li 上启动点击事件,但它似乎不起作用。

$( document ).ready(function() {
   $("#menu ul li").click(function(){
      alert(this.id);
   });
});
    .wrapper {
     display: grid;
        grid-template-columns: 2fr 7fr 2fr;
        grid-template-areas: 
          "left header  header"
          "left    content ad"
          "left    content ad"
          "footer footer  footer"
       }
    
    .header{
     grid-area:header;
     position: sticky;
     top:0;
     background-color: red;
     height: 100px;
     text-decoration: none;
    }
    
    .left-sidebar{
     grid-area:left;
     top:0;
     background-color: #22262A;
        position: sticky;
        height: 100vh;
        padding:0px 0px 0px 0px;
        font-size: 26px;
        text-align:center;
    }
    
    .left-sidebar a{
     padding: 15px 0px 15px 0px;
     color:#000;
     display: block;
     text-decoration: none;
    }
    
    .nav a:hover{
     background-color: #272b30;
    }
    
    .ad{
     grid-area:ad;
     background-color: navy;
    }
    .content{
     grid-area:content;
     padding: 5px 5px 5px 5px;
     background-color: yellow;
     height: 100vh;
    }
    
    .footer{
     grid-area:footer;
     background-color: grey;
     height: 125px;
    }
    
    #logo{
     margin-top: 50px;
     margin-bottom: 50px;
    }
    
    .no-list{
     display: block;
     text-decoration: none;
    }
    
    #menu ul li{
     background-color: yellow;
     z-index: 500;
    }
<html>
<head>
 <link rel="stylesheet" type="text/css" href="assets/css/style.css">
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
 <script src="assets/js/main.js"></script>
</head>
<body>
<div class="wrapper">
 <div class="header">
 </div>
 <div class="ad">advertisements</div>
 <div class="left-sidebar">
  <nav id="menu">
   <a href="#" data-target="home" class="" id="logo">Sylent</a>
   <ul class="nav" id="test2">
    <li id="getBierTest" onclick="alert()">try</li>
   </ul>
  </nav>
 </div>
 <div class="content">main content div</div>
 <div class="footer">footer div</div>
</div>
</body>
</html>

我在另一个项目中使用了它并且它起作用了。但是这次我使用的是 CSS 网格,突然间它没有了。任何想法可能是什么原因造成的? 提前致谢。

如果您要针对特定​​的用户,请尝试此操作

$("#menu ul li").on('click', function(){
   alert(this.id);
});

更优化的方案可以

$(document).on('click', '#menu ul li',function(){
   alert(this.id);
});

希望对您有所帮助

您的代码完全正确。但始终确保在页面完全加载后加载 JS。使用 $(document).ready() 函数来做到这一点。

$( document ).ready(function() {
   $("#menu ul li").click(function(){
      alert(this.id);
   });
});

我已将您的代码复制到 Codepen 中: https://codepen.io/chrisboon27/pen/NYYNvJ?editors=1111 我能看到的唯一问题是触发了两个警报。第一个是空的,但第二个有效。发生这种情况是因为除了通过 jQuery:

添加事件
$( document ).ready(function() {
   $("#menu ul li").click(function(){
      alert(this.id);
   });
});

您还在 html 中调用内联警报,但没有任何参数,因此您只会得到一个空警报:

<li id="getBierTest" onclick="alert()">try</li>

如果您删除内联警报,它可能对您有用。