I have the following code:
<ul class="cssdropdown">
<li class="headlink">RANGE
<ul class="innerDrop">
<li>Range Child</li>
<ul>
<li>
<li class="headlink">HOME
<ul class="innerDrop">
<li>Home Child</li>
<ul>
<li>
</ul>
I'm trying to toggle the <ul class="innerDrop"
with some jQuery. And I need to do it by adding a class the hide
class which has display:none
It hides fine, but when I click on the HOME or RANGE it opens both inner <li>
when开发者_开发技巧 I just want the one to open.
Here is my jQuery:
$(document).ready(function(){
$('li.headlink ul').addClass('hide');
$('#header').append('<div class=\"showpersonal\" onclick=\"toggleMenu()\"></div>');
$('#header').append('<div class=\"showbusiness\" onclick=\"toggleMenu()\"></div>');
});
function toggleMenu() {
$('li.headlink ul').toggleClass('hide', this);
}
you question was answered by nikc, just a hint from my side jQuery allows you to add a click handler on creating an element in a way like:
$('<div/>', {
class: 'showpersonal',
click: function(e){
$(this).find('li.headlink ul').toggleClass('hide');
}
}).appendTo('#header');
Your jquery
$('li.headlink ul').toggleClass('hide', this);
will find all ul
lists inside any li.headlink
anywhere in the DOM. Change it to
$(this).find('li.headlink ul').toggleClass('hide');
and it should work as expected, as long as this
refers to the correct node. To be sure of that, you can add this
as a parameter to toggleMenu
in the event trigger and edit the toggleMenu
function accordingly.
// Event trigger
onclick="toggleMenu(this);"
// Event handler
function toggleMenu(node) {
$(node).find('li.headlink ul').toggleClass('hide');
}
Then it's arguable if the click event is the best way to open a submenu. The common way to do it is - IMHO - to open the submenu on hovering. But that's, of course, subjective.
Here's an example
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('li.headlink ul').addClass('hide');
$('li.headlink').click(function(){
$(this).children('ul').toggleClass('hide');
});
});
</script>
<style type="text/css">
.hide{display:none;}
</style>
</head>
<body>
<ul class="cssdropdown">
<li class="headlink">RANGE
<ul class="innerDrop">
<li>Range Child</li>
</ul>
</li>
<li class="headlink">HOME
<ul class="innerDrop">
<li>Home Child</li>
</ul>
</li>
</ul>
</body>
</html>
精彩评论