问题
HTML code for dropdowns:
<ul>
<li class="dropDownLink">
Locality
<ul class="dropDown">
<li class="dropDown-row"><input tpye="text"></li>
</ul>
</li>
<li class="dropDownLink">
Locality
<ul class="dropDown">
<li class="dropDown-row"><input tpye="checkbox"> Option 1</li>
<li class="dropDown-row"><input tpye="checkbox"> Option 2</li>
<li class="dropDown-row"><input tpye="checkbox"> Option 3</li>
</ul>
</li>
</ul>
jquery Code to show dropdown:
$('.dropDownLink').on('click', function () {
$('.dropDown').hide();
$(this).children($('.dropDown')).show();
});
jQuery to hide dropdowns on clicking outside dropdown:
$(document).on('click', function (e) {
if(!$('.dropDownLink').is(e.target) && !$('.dropDown').is(e.target)) {
$('.dropDown').hide();
}
});
When clicking on document other than dropdown its working fine but clicking on content inside dropdown its hiding its parent dropdown. There are some form contents as well in dropdown like input textfield, checkboxes and links. Dropdown should not hide clicking on these elements inside dropdown.
Please help me with this. Thanks in Advance.
回答1:
Updated with exact solution: The advice of super specific DOM element targeting still stands. jsFiddle Example
var $dropShow = function showList() {
$('.dropDownLink').on('click', function () {
$('.dropDown').hide();
$(this).children($('.dropDown')).show();
});
};
var $navSelections = $('li.dropDown-row input, li.dropDown-row, ul.dropDown li.dropDown-row input, li.dropDownLink, ul li.dropDownLink');
var $bodyClick = function hideAll() {
$(this).on('click', function (e) {
if (!$navSelections.is(e.target)) {
$('.dropDown').slideUp(150);
}
});
};
$('.dropDownLink').not($navSelections).click($dropShow());
$('*').not($navSelections).click($bodyClick());
Pinpoint the pathing that you want the action to occur on only. If it is only supposed to occur, for example on a div, then use $('div.dropDownLink')
. If it is only links in say, a navMenu that you want this functionality applied to, then you use $('navMenu div.dropDownLink')
. Essentially, the more accurate your selector the better the results will be.
If however, you would like to take the not so accurate approach you can use the .not()
method to leave out very specific things.
var $parentOfDropDown = $('div#navMenu');
$('.dropDown').not($parentOfDropDown).hide();
来源:https://stackoverflow.com/questions/31765167/clicking-on-dropdown-content-dropdown-getting-hide