简体   繁体   English

jQuery活动的父级li在单击子级li

[英]jQuery active parent li on click child li

I'm trying to add active class to parent li after clicking on link in child li . 单击子li链接后,我试图将活动类添加到父li中。 I have drop down menu, on my drop down menu HTML code is in following website: http://www.dawntravels.com/ 我有下拉菜单,下拉菜单中的HTML代码位于以下网站: http : //www.dawntravels.com/

I've tried this code without success: 我尝试了以下代码但未成功:

<script>
    $(".arrow_carrot-2right").click(function (e) {
         e.preventDefault();
         $(this).closest('li').addClass('selected'); // I also tried .parent().addClass
    });
</script>

HTML: HTML:

<ul class="arrow_carrot-2right">
    <li><a href="#">Home</a></li>
     <li><a href="#">Services</a></li>
     <li><a href="#">Contact Us</a></li>
</ul>

JQuery: JQuery的:

$('.arrow_carrot-2right > li').click(function () {    
$(this).addClass('selected').siblings().removeClass('selected');
});

CSS: CSS:

.selected{
    background-color:green;
}

Demo: 演示:

http://jsfiddle.net/bS75H/ http://jsfiddle.net/bS75H/

As your class arrow_carrot-2right applied in <i> not on anchor tag so try this, 由于您的class arrow_carrot-2right适用于<i>而不是anchor tag因此请尝试此操作,

$('ul.sf-menu li a').on('click',function(e){
   e.preventDefault();
   $(this).closest('li').addClass('selected');
});

Try: 尝试:

//get the current URL
var url = window.location;
//after the link has been clicked and page loaded,
//find the clicked anchor tag using the loaded page name
$('.sf-menu a').filter(function() {
   return this.href == url;
//add the 'active' class to the outermost parent <li> of the matched <a> tag
}).parents("li").addClass('active');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM