I have a menu like this;
<ul>
<li><a>1</a></li>
<li><a>2</a>
<ul>
<li><a>3</a></li>
<li><a>4</a></li>
<li><a>5</a></li>
<li><a>6</a>
<ul>
<li><a>7</a></l开发者_运维百科i>
<li><a>8</a></li>
<li><a>9</a></li>
</ul>
</li>
</ul>
<li><a>10</li>
</ul>
If i want to make an selection on the 2nd level with jQuery.
$('ul li ul li') { action() }
But when i do this, this action will also be adopted by it's children, (ul li ul li ul li) i don't want that to happen.
I just want to select (ul li ul li).
With jQuery, how do i make it work?
The easiest way to solve this is to give the outer <ul>
a CSS class identifier or id. Then use the direct descendents selector
$('ul.className > li > ul > li') // CSS class className
or
$('#id > li > ul > li') // id id
$('ul > li > ul > li').action()
But you'll need to anchor the top-level ul
somehow... with an ID, for example.
$('#menu > li > ul > li').action()
But when i do this, this action will also be adopted by it's children, (ul li ul li ul li) i don't want that to happen.
Use eq
selector to target a specific li:
$('#mainmenu li ul li').eq(5)............
Or its variation:
$('#mainmenu li ul li:eq(5)')............
Are you talking about a click handler that applies only to the element itself and not the elements contained in it? I'd suggest using classes and adding a click handler to the subelements that prevents the event from bubbling up using stopPropagation. The latter is needed because when you click on the inner element the event will also be fired on its parent. If you really only want the handler to be invoked when you click on the element itself and none of its children, then you need to stop the event from bubbling up.
$('ul.secondlevel li').click( function() {
// do something
} );
$('ui.thirdlevel li').click( function(e) {
// do something else
e.stopPropagation();
});
Do you mean that you want to select the li
s containing 3, 4, 5 and 6?
If so, give their parent (second level) ul
s an id and use the direct descendent selector with it:
$('ul#second_level_ul > li')
精彩评论