javascript - 在javascript类中获取文档计数列表

标签 javascript html

This is the html

<ul id="List">
   <li><h2>Numeros Primos</h2></li>
   <li>Hello World</li>
   <li>Not Work</li>
</ul>
<p id="count"></p>

This is the javascript

class List {
        static Restart() {
            document.getElementById("List").innerHTML = "<li><h2>Numeros Primos</h2></li>";
        }
        static add(Number) {
            document.getElementById("List").innerHTML += "<li>" + Number + "</li>"
        }
        get count() {
            return document.getElementById("List").childElementCount
        }
    }

    document.getElementById("count").innerHTML = List.count;
    // return undefined

PROBLEM

I can't get count number in the list

it return "undefined"

最佳答案

使计数静态 :)

class List {
        static Restart() {
            document.getElementById("List").innerHTML = "<li><h2>Numeros Primos</h2></li>";
        }
        static add(Number) {
            document.getElementById("List").innerHTML = document.getElementById("List").innerHTML + "<li>" + Number + "</li>"
        }
        static get count() {
            return document.getElementById("List").childElementCount;
        }
    }

    document.getElementById("count").innerHTML = List.count;
<ul id="List">
   <li><h2>Numeros Primos</h2></li>
   <li>Hello World</li>
   <li>Not Work</li>
</ul>
<p id="count"></p>

关于javascript - 在javascript类中获取文档计数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905506/

相关文章:

javascript - 将对象数组传播到父对象中

javascript - 如何将事件类添加到 onclick 元素?

html - Tahoma 字体系列不适用于移动设备

javascript - 将脚本添加到主体加载后运行的头部

javascript - 动态获取数据目标

html - 修复 CSS 和 HTML 显示布局

javascript - 如何更改滚动上的 div 位置(取决于滚动方向)?

html - 表格中的 SVG 在 Internet Explorer 中不缩放

html - 100% 宽度大于父级的 div

javascript - Dojo - xhrPut 中变量赋值发生得太晚