下拉列表mouseleave隐藏后点击按钮无法重新显示的问题求助
Hey, let's sort out why your dropdown stays hidden after clicking the trigger button again!
The core issue here is that your click handler isn't targeting the correct dropdown menu element. Let me break this down and fix it for you.
What's Going Wrong
Looking at your code:
- Your dropdown menu has an ID of
links, but the button'svalueattribute is set torowId. When you click the button, your JavaScript tries to show$('#' + idP)— whereidPis the button's value — meaning it's searching for an element with IDrowId, which doesn't exist. That's why clicking the button does nothing after the dropdown gets hidden onmouseleave!
Fixed Code Options
Option 1: Direct Targeting (Simple for Single Dropdown)
If you only have this one dropdown to handle, you can directly reference its ID in the click handler:
$('ul.dropdown-menu').on('mouseleave', function(e) { $(this).hide(); }); $('.icm-link').on('click', function(event) { // Prevent Bootstrap's default dropdown behavior from interfering event.preventDefault(); // Show the correct dropdown menu $('#links').show(); });
Option 2: Dynamic Targeting (Better for Multiple Dropdowns)
If you plan to have multiple buttons paired with different dropdowns, add a data-target attribute to the button to specify which dropdown it controls. This makes your code scalable:
First, update the button HTML:
<button data-target='links' data-value='shellId' type="button" style='color: #2f84ff;height: 30px !important;width: 40px !important;' value='rowId' class="btn btn-default btn-xs dropdown-toggle icm-link" data-toggle="dropdown"> <span class='glyphicon glyphicon-share-alt' style='color: #2f84ff;' aria-hidden='true'></span> </button>
Then adjust the JavaScript:
$('ul.dropdown-menu').on('mouseleave', function(e) { $(this).hide(); }); $('.icm-link').on('click', function(event) { event.preventDefault(); const targetDropdownId = $(this).attr('data-target'); // Fetch the dropdown ID from the button shellID = $(this).attr('data-value'); $('#' + targetDropdownId).show(); });
Quick Tip
Since you're using Bootstrap's dropdown-toggle class, the framework has its own built-in dropdown behavior. Adding event.preventDefault() ensures your custom click logic takes precedence and avoids conflicts with Bootstrap's default handling.
内容的提问来源于stack exchange,提问作者Mert Silva

