How to capture child links clicked using jquery?
I am trying to capture the event when a child element link is clicked and add class called "highlightchild" to it. Also I want to check if there are any child element link exist or not, if no child element exits ie "third level" highlight with "highlightparent" the parent. How can I do that using jquery?
$(document).ready(function() {
$('.menu ul').hide();
$('.menu .arrowUp').click(function() {
$('.menu ul').hide();
$(this).find(".third-level").toggle();
});
});
html
<ul class="menu">
<li class="arrowUp"><a href="#">link1</a>
<ul class="third-level" >
<!-- third level non-active -->
<li class="arrowUp"><a href="/somelink/">Some Link</a></li>
</ul>
</li>
<li class="arrowUp"><a href="#">link2</a>
<ul class="third-level" >
<!-- third level non-active -->
<li class="arrowUp"><a href="/links2/">some Links 2</a></li>
</ul>
</li>
<li class="arrowUp"><a href="#">link3</a>
<ul class="third-level" >
<!-- third level non-active -->
<li class="arrowUp"><a href="/Agri/">Agricultural</a></li>
<!-- third level non-active -->
<li class="arrowUp"><a href="/sugar/">Sugar</a></li>
<!-- third level non-active -->
<li class="arrowUp"><a href="/bbc/">Coffee</a></li>
<!-- third level n开发者_JAVA百科on-active -->
<li class="arrowUp"><a href="/cnn/">Energy</a></li>
<!-- third level non-active -->
<li class="arrowUp"><a href="funstuff">Fun stuff</a></li>
</ul>
</li>
<li class="arrowUp"><a href="#">link4</a></li>
<li class="arrowUp"><a href="#">link5</a></li>
<li class="arrowUp"><a href="#">link6</a></li>
</ul>
Not sure what you meant with your second part (could rephrase it and/or clarify?), but I would use .delegate()
:
$('ul.menu').delegate('a', 'click', function() {
$('ul.menu .highlightchild').removeClass('.highlightchild');
$(this).addClass('.highlightchild');
});
This adds only one event handler to the root of the menu.
// add hightlightChild class to children anchor tags on click
$('.parent_link > a').click(function(){
$(this).addClass('highlightChild');
return false; // or not if you want to follow the link
});
// loop over each parent link and highlight it if no children links exist
$('.parent_link').each(function(){
if ( $(this).children('a').size() > 0 ){
$(this).addClass('highlightParent');
}
});
How about:
$(".arrowUp > a").bind("click", function(event) {
event.preventDefault();
if ($(this).closest(".third-level").length > 0 ||
$(this).siblings().length === 0) {
$(this).addClass("highlight");
}
});
All links with a parent with class third-level
, or links with no sibling a
s.
http://jsfiddle.net/andrewwhitaker/bMupR/
Edit: Didn't notice you wanted different parent/child highlight classes, here's how you would do that:
$(".arrowUp > a").bind("click", function(event) {
event.preventDefault();
if ($(this).closest(".third-level").length > 0) {
$(this).addClass("childhighlight");
}
else if ($(this).siblings().length === 0) {
$(this).addClass("parenthighlight");
}
});
http://jsfiddle.net/andrewwhitaker/bMupR/1/
精彩评论