简体   繁体   English

如何将所有ul和li保留在父li下:selected,但删除其他导航项

[英]How do I keep all ul and li's under a parent li:selected, but remove other navigation items

I need to only keep the UL & LIs under the selected parent, but remove any others that occur before or after. 我只需要将UL和LI保留在选定的父项下,而删除在此之前或之后发生的所有其他事件。

For example, given: 例如,给定:

<ul id="fruit">
    <li class="selected"> Red </li>
        <ul> Sweet </ul>
            <li> Cherry </li>
            <li> Apple </li>
        <ul> Tart </ul>
    <li> Yellow <li>
    <li> Green </li>

I need: 我需要:

    <li class="selected"> Red </li>
        <ul> Sweet </ul>
            <li> Cherry </li>
            <li> Apple </li>
        <ul> Tart </ul>

I have tried $(".fruit li:not(.selected)"); 我已经尝试过$(“。fruit li:not(.selected)”); however that removes all the children li and ul included. 但是,这会删除所有包含li和ul的孩子。 I also tried 我也试过

$( document ).ready(function() {

  $('.s4-ql li').each(function(){
    if($(this).parent.attr('selected') == 'selected'){
    $(this).css("display", "initial");
    }
else {
  $(this).css("display", "none");

}
});

Thanks! 谢谢!

Assuming you correct your HTML to valid HTML like this: 假设您将HTML更正为有效的HTML,如下所示:

<ul id="fruit">
    <li class="selected"> Red 
        <ul>
            <li> Sweet </li>
            <li> Cherry </li>
            <li> Apple </li>
            <li> Tart</li> 
      </ul>
    </li>
    <li> Yellow </li>
    <li> Green </li>
</ul>

Then you can detach your selected like this. 然后,您可以像这样分离您选择的对象。

var $selected = $('#fruit').find('.selected').detach();

It's a simple remove() of the $('#fruit') from there and your selected is the part you wanted to keep. 这是一个简单的$('#fruit')的remove(),您选择的就是您想要保留的部分。 https://jsfiddle.net/n25qbmLo/ https://jsfiddle.net/n25qbmLo/

It looks like your Sweet and Tart are subheaders so if that's true your HTML should be like this: 看起来您的Sweet和Tart是子标题,因此,如果是这样,您的HTML应该是这样的:

<ul id="fruit">
    <li class="selected"> Red 
        <ul>
          <li> Sweet 
              <ul>
                <li> Cherry </li>
                <li> Apple </li>
              </ul>
          </li>
          <li> Tart</li> 
      </ul>
    </li>
    <li> Yellow </li>
    <li> Green </li>
</ul>

https://jsfiddle.net/n25qbmLo/2/ https://jsfiddle.net/n25qbmLo/2/

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

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