简体   繁体   English

根据李的风格(背景图像)设置李的ul的班级名称吗?

[英]Set class name for li's ul based on the li's style (background-image)?

i have the menu structure like below, 我的菜单结构如下

<ul>

<li style="background-image:ur('open.gif');">
      <ul class="sub-menu">
         ...........
      </ul>
</li>

<li>
      <ul class="sub-menu">
         ...........
      </ul>
</li>

<li>
      <ul class="sub-menu">
         ...........
      </ul>
</li>
</ul>

the first li which has style="background-image:ur('open.gif');" 第一个具有style =“ background-image:ur('open.gif');”的li is displayed with dropdown now. 现在显示带有下拉菜单。

if i click in other li's the style will apply that li's also style="background-image:ur('open.gif');" 如果我单击其他li的样式,则将应用li的样式,同样也是style =“ background-image:ur('open.gif');”

Now two li's display it's dropdown li's. 现在,两个li的显示是下拉li的显示。

i Need to do is if one li is set with style="background-image:ur('open.gif');" 我需要做的是,如果一个li设置为style =“ background-image:ur('open.gif');” this one. 这个。 if i click another li, i need to set previous li's UL style display:none which is with style style="background-image:ur('open.gif');". 如果我单击另一个li,则需要设置先前li的UL样式display:none,其样式为style =“ background-image:ur('open.gif');”。

How can i do this? 我怎样才能做到这一点?

You better add a class "open" to the LI and handle the URL with CSS. 最好将一个“ open”类添加到LI,并使用CSS处理URL。

Example with JS: JS示例:

$(function(){
    $("#menu").children().hover(function(){
        $(this).addClass("open");
    },
    function(){
        $(this).removeClass("open");
    });
});

CSS 的CSS

#menu li
{
    background-image:url('closed.gif');
}

#menu li.open
{
    background-image:url('open.gif');
}

Example without JS 没有JS的示例

#menu li ul
{
    display: none;
    background-image:url('closed.gif');
}
#menu li:hover ul
{
    display: block;
    background-image:url('open.gif');
}

If I've understood your problem correctly, this should work: 如果我正确理解了您的问题,那么应该可以:

$("LI").click(function() {
    $("LI").css("background-image", "none");
    $(this).css("background-image", "url('open.gif')");
});

Adding and removing a class would be more appropriate here as it would mean you can control the image shown in the background from your stylesheet without needing to change your code (this is called separation of concerns). 在此处添加和删除类更为合适,因为这意味着您可以从样式表控制后台显示的图像,而无需更改代码(这称为关注点分离)。

$("LI").click(function() {
    $("LI").removeClass("open");
    $(this).addClass("open");
});

CSS: CSS:

.open { background-image: url('open.gif'); }

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

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