获取 li 项的状态最大值

Get the maximum value of state for li items

本文关键字:状态 最大值 li 获取      更新时间:2023-09-26

假设,我有一个选项卡的无序列表,如下所示:

<ul>
    <li>...</li>
    <li>...</li>
    <li>...</li>
</ul>

现在,我正在根据点击将列表设置为活动列表。因此,当用户单击li时,它将被标记为活动,并且this.state.selected将等于li的数量。例如,单击第一个lithis.state.selected将等于1,依此类推。

有没有办法找出所选可能maximum state

例如,如果ul有三个li标签,则selectedmaximum state将为3

假设this是对<ul>的引用,我建议:

this.state.maximum = this.children.length;

或者,如果可能有不计算的子项,则可以将 CSS 选择器传递给querySelectorAll(),以仅检索要查找的子项:

this.state.maximum = this.querySelectorAll('li.classToFind').length;

或者,您可以使用Array.prototype.filter()根据元素节点的属性仅保留那些要计数的元素,例如仅保留那些属性"keep"等于"true"的元素节点(作为一个简单的演示):

// Array.from() turns the NodeList returned by this.children
// into an array, in order to easily use the methods of the
// Array prototype,
// Array.prototype.filter() is used to filter out those elements
// for which the assessment in the anonymous function returns a
// false, or falsey, value:
this.state.maximum = Array.from( this.children ).filter(
  function(node){
    return node.keep === true;
  }).length;

或者,重写上述内容以使用箭头函数:

this.state.maximum = Array.from( this.children )
                          .filter( n => n.keep === true ).length;

有没有办法找出可能的最大状态 选择?

例如,如果 ul 有三个 li 标签,则 选择将为 3。

所以,你想知道ul的孩子数量吗?

<ul id="ul1">
    <li>...</li>
    <li>...</li>
    <li>...</li>
</ul>

这么多代码应该做

alert( document.getElementById( 'ul1' ).children.length );