简体   繁体   English

隐藏下拉菜单 OnClick

[英]Hide a dropdown menu OnClick

I have a dropdown menu, one of the options executes Ajax to show data in another Div. 我有一个下拉菜单,其中一个选项执行 Ajax 以显示另一个 Div 中的数据。

I want to hide the dropdown menu (close it) when this option is clicked.单击此选项时,我想隐藏下拉菜单(关闭它)。

// hide the menu when an example is clicked
$(".dropdown-item").on("click", function(){
    $(".dropdown-menu").hide(); 
});

I have tried the below which I found online, but it doesn't seem to close the menu:我已经尝试了我在网上找到的以下内容,但它似乎没有关闭菜单:

 // hide the menu when an example is clicked $(".dropdown-item").on("click", function(){ $(".dropdown-menu").hide(); });

 $( document ).ready(function() { debugger; var ele=$(".dropdown-content"); $(".dropdown-content a").click(function(){ if(this.innerText=="Link 2"){ $(".dropdown-content").hide(); $(".dropbtn").hide(); } }); });
 .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; }.dropdown { position: relative; display: inline-block; }.dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; }.dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; }.dropdown-content a:hover {background-color: #f1f1f1}.dropdown:hover.dropdown-content { display: block; }.dropdown:hover.dropbtn { background-color: #3e8e41; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>Dropdown Menu</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div>

You hide a dropdown menu like this and if you want to show simply add show functionality.您可以隐藏这样的下拉菜单,如果您想显示,只需添加显示功能。

Try this toggle method should work试试这个切换方法应该有效

<a href="#" onclick="handleClick()"  class="btn btn-floating" data-toggle="dropdown">
    how/hide menu
</a>

function handleClick(){
    
   $(".dropdown-menu").toggle(); 
    
}

refer to this link for running example:请参阅此链接以获取运行示例:

https://playcode.io/647558/ https://playcode.io/647558/

Just remove class 'show' from dropdown:只需从下拉列表中删除 class 'show' :

// hide the menu when an example is clicked
$(".dropdown-item").on("click", function(el){
    $(el.target).parents(".dropdown").removeClass("show"); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM