如何使用JavaScript/jQuery关闭下拉列表?

e0bqpujr  于 2023-04-20  发布在  jQuery
关注(0)|答案(2)|浏览(102)

我试图在点击一个选项时关闭一个HTML下拉列表。该列表使用CSS悬停显示。当光标移开时,它会消失,但当点击一个选项时不会。
这里有一个小提琴显示的问题:https://jsfiddle.net/evL5d8aq/
我需要的可点击元素是一个DIV或一个表格单元格。小提琴显示都表现出同样的问题。
单击事件触发OK。我已经尝试了几种方法来关闭列表,但都不能令人满意地工作,如我在JS中添加的注解所示。
我用的是Bootstrap 4
HTML:

<table class="table table-bordered">
<tbody>
  <tr>
    <td class="text-center dropdown custom-dropdown" style="background-color: red">JavaScript
      <ul class="dropdown-menu custom-dropdown-list mt-0">
        <li class="text-center" style="background-color: lightgreen;">HTML</li>
        <li class="text-center" style="background-color: yellow;">CSS</li>
        <li class="text-center" style="background-color: lightblue;">C#</li>
      </ul>
    </td>                    
  </tr>
</tbody>
</table>
<div style="background-color: red" class="text-center dropdown custom-dropdown">
JavaScript
<ul class="dropdown-menu custom-dropdown-list mt-0">
        <li class="text-center" style="background-color: lightgreen;">HTML</li>
        <li class="text-center" style="background-color: yellow;">CSS</li>
        <li class="text-center" style="background-color: lightblue;">C#</li>
      </ul>
</div>

JS:

$('.custom-dropdown').on('click', function(e) {

    console.log("You selected: " + e.target.innerText)

    // Works, but then can't invoke dropdown
    //$('.dropdown-menu').css({'display': 'none'});

    // Hides the TD or Div as well as the DDL
    //$(this).hide();

    // Does nothing
    $(".custom-dropdown-list").removeClass("open");  

});
xkrw2x1b

xkrw2x1b1#

你应该使用这个代码:

$('.dropdown').on('mouseenter', function(e) {
  $(this).find('.dropdown-menu').addClass('open')
}).on('mouseleave', function(e) {
  $(this).find('.dropdown-menu').removeClass('open')
})

$('.dropdown-menu li').on('click', function(e) {
  $(this).parent().removeClass('open')
})

你应该加上CSS

.dropdown-menu.open {
    display: block;
  }

并删除与悬停效果相关的CSS https://jsfiddle.net/jfagLrxp/23/

egmofgnx

egmofgnx2#

尝试切换-

<script type="text/javascript">$(document).on('click', '.list > li ', function () {
$(this).next('.list').children().toggle();
})</script>

相关问题