clicking on dropdown content, dropdown getting hide

风格不统一 提交于 2019-12-20 03:26:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!