【问题标题】:Stop parent element onclick propagation but allow dropdown open/close and menu item events for Bootstrap dropdown?停止父元素 onclick 传播,但允许 Bootstrap 下拉菜单的下拉菜单打开/关闭和菜单项事件?
【发布时间】:2016-09-14 22:51:52
【问题描述】:

我有一个带有select 选项的jQuery DataTables 表(单击时选择行)。我遇到的问题是单击下拉按钮和下拉菜单项会导致选择基础行。 如何防止底层的td/tr/DataTable select点击事件,但允许dropdown及其菜单项(li a子项)点击事件?

<table id="datatable">
  <tr>
    <td>
      <div class="dropdown">
        <button type="button" class="dropdown-toggle" data-toggle="dropdown">
          <i class="fa fa-caret-down"></i>
        </button>
        <ul class="dropdown-menu">
          <li><a href="#" class="action">Action</a></li>
        </ul>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <div class="dropdown">
        <button type="button" class="dropdown-toggle" data-toggle="dropdown">
          <i class="fa fa-caret-down"></i>
        </button>
        <ul class="dropdown-menu">
          <li><a href="#" class="action">Action</a></li>
        </ul>
      </div>
    </td>
  </tr>
</table>

<script>
  $("#datatable").DataTable({ select: true });
</script>

我尝试使用e.stopPropagation(),但这会阻止下拉菜单显示

<script>
  $("#dataTable tbody").on("click", "button", function (e) {
    e.stopPropagation(); // this prevents dropdown menu from showing
  });
</script>

我也尝试过手动切换下拉菜单,但是这引入了奇怪的下拉行为(例如,单击某一行的下拉按钮会显示其下拉菜单,但没有隐藏任何其他行的已经存在的下拉菜单打开):

<script>
  $("#dataTable tbody").on("click", "button", function (e) {
    $(this).closest("div.dropdown").toggleClass("open"); // weird effects
    // or:
    $(this).closest("div.dropdown").find("ul.dropdown-menu").toggle(); // weird effects

    e.stopPropagation();
  });
</script>

我也试过dropdown("toggle"),虽然这解决了上述奇怪的行为,但它仍然阻止了菜单项的点击事件

<script>
  $("#dataTable tbody").on("click", "button", function (e) {
    // no weird behavior, but now menu item click events are disabled
    $(this).closest("div.dropdown").find("ul.dropdown-menu").dropdown("toggle");

    e.stopPropagation();
  });
</script>

【问题讨论】:

    标签: twitter-bootstrap drop-down-menu datatables event-propagation


    【解决方案1】:

    事实证明jQuery DataTables 为此类情况提供了事件处理程序user-select.dt。我能够获得正确使用以下各项所需的所有功能:

    <script>
      $("#datatable").DataTable({
        select: true
      }).on("user-select.dt", function (e, dt, type, cell, originalEvent) {
        var $elem = $(originalEvent.target); // get element clicked on
        var tag = $elem[0].nodeName.toLowerCase(); // get element's tag name
    
        if (!$elem.closest("div.dropdown").length) {
          return; // ignore any element not in the dropdown
        }
    
        if (tag === "i" || tag === "a" || tag === "button") {
          return false; // cancel the select event for the row
        }
      });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 2019-12-05
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2020-02-11
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多