I have a basic list-item with an embedded list that I'd like to open when I double click anywhere in the li that isn't the embedded ul.
<ul>
<li class="first_level">
<span class="name">List Name</span>
<ul class="tools"></ul>
<ul class="sublist">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
</ul>
</li>
</ul>
In the example above I would like to have any where in .first_level to be attached to dblclick to toggle the .sublist to visible and not visible but I don't wan开发者_JAVA百科t this to happen if I dblclick on .tools, .sublist, or .name.
Basic code:
$('.first_level, .first_level :not(*)').dblclick(function(e){
$(this).find('.sublist').toggle();
});
I thought my :not(*) would tell it not to attach it to the children but it didn't work. My .first_level has a min-height so my initial idea also had me check the coordinates of the click event within the element and if it was within the min-height to toggle. That solved the problem of it grabbing in the sublist but my tools and name was still a problem (not the best solution but it was succint). So what selector am I forgetting to use here?
http://jsfiddle.net/8PNEn/1/
Just make sure the double-click is done on .first_level
$('.first_level').dblclick(function(e) {
if ($(e.target).hasClass('first_level')) {
$(this).find('.sublist').toggle();
}
});
http://jsfiddle.net/8PNEn/9/
You're probably going to have to do a little bit of logic in your handler, rather than relying on the selector. Perhaps this, using closest
and is
:
$('.first_level').dblclick(function(e) {
if ($(e.target).closest('li').is(this)) {
$(this).find('.sublist').toggle();
}
});
This starts from the event target (the element that was double-clicked), then traverses up the tree to find the nearest li
element, and then sees whether that li
element is the element where the function is handled, i.e. .first_level
. If it is, then the sublist is toggled.
jsfiddle
Have you tried canceling the event propagation for the name tools and sublist dom? It would look something like this:
// attach double click to first level dom
$('.first_level').dblclick(function(e){
$(this).find('.sublist').toggle();
});
// cancel even propagation for name, tools, and sublist dom
$('.name, .tools, .sublist').dblclick(function(e){
e.stopPropagation();
});
http://jsfiddle.net/DbuQ5/
Would that be a good way to do it : http://jsfiddle.net/DavidLaberge/8PNEn/6/
Because my live code doesn't actually have the .first_level class I ended up using a hybrid solution between the accepted answer and the one that currently has the most up-votes. I decided to post my solution as an answer and not edit my question just to stay consistent with the site's functionality :)
$('ul > li').dblclick(function(e) {
if (e.target == this) {
$(this).find('.sublist').toggle();
}
});
精彩评论