jQuery li:has(ul) selector issue
I was creating a tree using UL LI list and jQuery. I used a jQuery Selector
jQuery(li:has(ul)) to find all the list nodes having childs and then added a click e开发者_JS百科vent to it.
jQuery(li:has(ul)).click(function(event) {
jQuery(this).children.toggle();
jQuery(this).css("cursor","hand");
});
This works for me except i dont understand why i get a cursor hand and click event triggering even when i take mouse pointer to childs of my selected li
<li> Parent // it works here that is fine
<ul>
<li> child1 // it works here i dont understand need explanation
</li>
<li> child2 // it works here i dont understand need explanation
</li>
</ul>
</li>
What you are seeing is event bubbling. When you click on a descendant element, the event also bubbles up to its ancestors. Your click handler on the ancestor element is what is being triggered. If you don't want this, you'll need to also stop event propagation in the click handlers of the child elements to prevent the event from bubbling up.
jQuery(li:has(ul)).children().find('li').click(function(e) {
e.stopPropagation();
});
The cursor
property and the click
event are inherited by the element's children.
To prevent the cursor
property from being inherited, you can add a CSS rule that explicitly sets the cursor for <ul>
and <li>
elements, like this:
ul, li {
cursor: default;
}
To prevent the click event from firing for the children, you can check event.target
, like this:
if (event.target !== this) return;
yea try
jQuery('ul',this).css("cursor","hand !important");
.// to tell it to apply the cursor to the ul elements with "this" i.e the original li element
精彩评论