简体   繁体   English

计数没有CSS类的子菜单项jQuery

[英]Counting Sub-Menu Items jQuery without CSS Classes

The great Google and SO didn't render search results regarding this. 伟大的Google和SO并未提供与此相关的搜索结果。 Some were similar but didn't quite get me there. 有些是相似的,但并没有让我到达那里。

I am in need of making a classless submenu that will attach a style attribute to each individual <li> in the sub <ul> in order to set a min-width property based on the number of sub list items. 我需要制作一个无类的子菜单,该子菜单将为style <li>属性<li>附加到sub <ul>中的每个单独的<li> <ul> ,以便根据子列表项的数量设置最小宽度属性。

The HTML HTML

<nav>
<ul>
  <li><a href="#">HOME</a></li>
  <li><a href="#">ABOUT COMPANY</a></li>
  <li>
    <a href="#" class="sub">ABOUT PRODUCT</a>
    <ul>
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
    </ul>
  </li>
  <li><a href="#">GETTING STARTED</a></li>
  <li>
    <a href="#" class="sub">PATIENT SUPPORT</a>
    <ul>
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
      <li><a href="#">Item 3</a></li>
    </ul>
  </li>
  <li><a href="#">CONTACT</a></li>
  <li><a href="#">eUPDATES</a></li>
</ul>
</nav>

The JavaScript JavaScript

$('.sub').text(function() {
    var count = $(this).next().find('li').length;
    var totalwidth = count * 115;
    $(this).next().find('li').parent('ul').attr('style','min-width:'+totalwidth+'px');
});

I need to be able to do this without searching based off the class "sub". 我需要能够做到这一点而无需基于类“ sub”进行搜索。 I've tried a few times, but none of it seems as powerful as the code I'm currently using. 我已经尝试了几次,但似乎都没有我现在使用的代码强大。 The backend developer I'm working with is requiring it to all be simple <ul><li></li></ul> structure with no classes. 我正在使用的后端开发人员要求它都必须是简单的<ul><li></li></ul>结构,没有类。

If anyone can help point me in the right direction on this, I'd greatly appreciate your time and help! 如果有人可以帮我指出正确的方向,我将非常感谢您的时间和帮助!

Target all LI items that contain UL's, find the number of LI's in those UL's, and multiply for width : 定位所有包含UL的LI项目,找到这些UL中LI的数量,然后乘以width:

$('ul', 'li').css('min-width', function() {
    return ( $(this).find('li').length * 115 ) + 'px';
});

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

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