问题描述:

I have an <ul> with plenty of <li>'s under it. Each of these <li>'s has a hidden <div class=dbox"> within. The structure/hierarchy for the <li>'s and their content is:

--> li

---->visible content (h3, img, p, etc.)

---->hidden div.dbox

-------> div.photos

-------> div.specs

When clicking the <li>'s image (always visible), <div class="dbox"> is then given display=block. So far so good. I then searched the web to get the .dbox to close whenever clicking outside it. I got this to work:

var mouse_is_inside = false;

$('.dbox').hover(function(){

mouse_is_inside=true;

}, function(){

mouse_is_inside=false;

});

$("body").mouseup(function(){

if(! mouse_is_inside) $('.dbox').hide();

});

Clicking outside .dbox now makes it close. So far so good. Next step was to add a 'close this window button for less tech-savy users, so, within the <div class="specs">, I added one last element, <span class="close"> then gave it this jquery code:

$('span.close').click(function() {

$(this).parent().parent().hide();

});

Which did not work. I tested with parents('.dbox') and it didn't work either. Funny enough, it is only when I target .dbox that hide doesn't work. If I do something like:

$(this).parent().hide();

which would close the containing div, <div class="specs">, it works and effectively closes <div class="specs">

I then thought that there was some sort of conflict with the 'click outside' code so I removed it and the bug remained...which leads me here to ask you knowledge-able fellows about this dilemma.

Thanks in advance

G.Campos

网友答案:

I got it to work: $(this).parents('.dbox').hide(1); It is only when hide() is empty that nothing happens. Adding 1 or whatever number does the trick. Why can't it be 0 though?

网友答案:

You can use the blur instead of your trick with mouse_inside.

Moreover, you can use the parents with a selector inside instead of your parent().parent().

Max

网友答案:

try

$(this).parent().parent().parent().hide(); // for button
网友答案:

One solution is you can set mouse_is_inside=false; in onMouseLeave event handler.

Another solution is to wire your event handlers like this:

$('.dbox').click(function(e) {
  // do stuff
  // ...

  // this will prevent the event from bubbling upto body's eventhandler
  e.stopPropagation();
});

$('body').click(function(e) {
  $('.dbox').hide();
});

Also, this should close the parent dbox div:

$('.dbox span.close').click(function() {
  $(this).parents('.dbox').hide();
});
相关阅读:
Top