首页 > 解决方案 > jQuery 3.4.1 .on()“单击”选择器包含ID和类

问题描述

我正在关注有关使用利用 Jquery 3.4.1 和 Bootstrap 4.4.1 的 Cordova 的教程。

该教程已有几年历史了,所以在我尝试联系教程的作者之前,我想我会尝试“SO”!(教程链接:http ://codingfix.com/anatomy-of-a-cordova-application-navigation-system-the-top-navigation-bar/ )

我假设这与 Cordova 无关,也可能与 Bootstrap 无关,a 纯粹与 Jquery 相关,但我想我会给你上下文。

问题:我在页面顶部有一个菜单。当我运行应用程序并点击菜单时,什么都没有发生。

$(document).on('click', '#cfx-topbar .cfx-topbar-menu', function() {
  alert("clicked!");
  var target = $(this).data('index');
  $('.carousel').carousel(target);
  switch (target) {
    case 0:
      //do here stuff specific to the view such as loading data...;
      break;
    case 1:
      //do here stuff specific to the view such as loading data...;    
      break;
    case 2:
      //do here stuff specific to the view such as loading data...;
      break;
    case 3:
      //do here stuff specific to the view such as loading data...;
      break;
  }
});
#cfx-topbar {
  background: #689F38;
  top: 0;
  left: 0;
  position: fixed;
  width: 100%;
  height: 50px;
  z-index: 3;
}

cfx-topbar-menu {
  list-style: none;
  position: relative;
  padding: 0;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="cfx-topbar">
  <ul id="cfx-topbar-menu">
    <li class="active"><a href="#" data-index="0"><i class="material-icons">dashboard</i></a></li>
    <li><a href="#" data-index="1"><i class="material-icons">group_work</i></a></li>
    <li><a href="#" data-index="2"><i class="material-icons">search</i></a></li>
    <li><a href="#" data-index="3"><i class="material-icons">share</i></a></li>
    <li><a href="#"><i class="material-icons">menu</i></a></li>
  </ul>
</div>

此代码不会触发。

我试过的:

如果我从选择器中删除“.cfx-topbar-menu”...

$(document).on('click', '#cfx-topbar', function () {

它着火了。

我敢肯定这不起作用有一个非常简单的原因,但我在网上搜索并找不到任何适合我的困境的东西,它在一个教程中。也许 Jquery 库已经改变并且这种组合已被取代?

标签: jquerycordovabootstrap-4

解决方案


这里有两个问题。首先,您尝试选择的属性是 a id,而不是 a ,因此选择器不class应该是。其次,该属性位于子元素上,因此您需要将其包含在选择器中。尝试这个:#cfx-topbar-menu.cfx-topbar-menudataa#cfx-topbar-menu

$(document).on('click', '#cfx-topbar #cfx-topbar-menu a', function() {
  var target = $(this).data('index');
  console.log(target);
});
#cfx-topbar {
  background: #689F38;
  top: 0;
  left: 0;
  position: fixed;
  width: 100%;
  height: 50px;
  z-index: 3;
}

cfx-topbar-menu {
  list-style: none;
  position: relative;
  padding: 0;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="cfx-topbar">
  <ul id="cfx-topbar-menu">
    <li class="active"><a href="#" data-index="0"><i class="material-icons">dashboard</i></a></li>
    <li><a href="#" data-index="1"><i class="material-icons">group_work</i></a></li>
    <li><a href="#" data-index="2"><i class="material-icons">search</i></a></li>
    <li><a href="#" data-index="3"><i class="material-icons">share</i></a></li>
    <li><a href="#"><i class="material-icons">menu</i></a></li>
  </ul>
</div>


推荐阅读