简体   繁体   English

jQuery-单击子元素但突出显示父级?

[英]jQuery - Click sub element but hightlight parent?

I have a html code like this: 我有这样的html代码:

<ul>
    <li class="curent"><a href="home.html">Home</a></li>
    <li>
        <a href="javascript:void(0)">Products</a>
        <ul class="sub">
           <li><a href="samsung.html">Samsung</a></li>
           <li><a href="lenovo.html">Lenovo</a></li>
         </ul>
    </li>
    <li><a href="catalog_grid.html">News</a></li>
</ul>

http://img38.imageshack.us/img38/5795/70a.png http://img38.imageshack.us/img38/5795/70a.png

I want to click any a tag and li tag parent is hightlighted. 我想单击任何标签,并且li标签的父级已突出显示。 I try this code but it doesn't work with a tag in ul has sub class: 我尝试了这段代码,但不适用于ul has子类中的标记:

var this_url = window.location.href;

$('#block_nav_primary ul li').each(function() {
    if ($(this).children().attr('href') == this_url) {
        $('#block_nav_primary ul').find('li[class="curent"]').removeClass('curent');
        $(this).addClass('curent');
    }
});

Can anyone point me in the right direction here? 有人可以在这里指出正确的方向吗?

Thanks for your help! 谢谢你的帮助!

P/S: it looks like this thread Highlight Parent Link in Navigation Menu With Jquery P / S:看起来像该线程使用jQuery在导航菜单中突出显示父链接

Try this: 尝试这个:

$("ul a").click(function () {
    $(this).parent().parent().addClass("blue");
});

or 要么

$("ul a").click(function () {
    $(this).closest("ul").addClass("blue");
});

CSS in both cases: 两种情况下的CSS:

.blue > a {
   color: blue;
}

JSFiddle to a quite similar scenario. JSF处于一个非常相似的场景。

I'm not sure I quite understand your wording, but you want to apply the same effect to all LI tags, including those in a sublist? 我不确定我是否完全理解您的措辞,但您想对所有LI标签(包括子列表中的那些标签)应用相同的效果吗?

Replace this: 替换为:

$('#block_nav_primary ul li').each(function() {

With this: 有了这个:

$('#block_nav_primary ul').find('li').each(function() {

Try 尝试

val items = $('#block_nav_primary ul li').click(function(){
    items.filter('.current').removeClass('current');
    $(this).addClass('current')
})

Why don't you try styling it such that the A tag takes the width of the entire LI tag and so when you click A tag, it would highlight the entire thing. 为什么不尝试设计样式,使A标签占据整个LI标签的宽度,因此当您单击A标签时,它将突出显示整个内容。 The CSS code for it would be something like: 其CSS代码如下所示:

li a {display: block; width: 100%; padding: 10px 0; background-color: pink;}
li a:hover {background-color: orange;}

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

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