HTML - DOM NodeList keys() 方法



HTML DOM NodeList 的 **keys()** 方法用於獲取一個迭代器,允許我們遍歷 NodeList 中包含的所有鍵。這些鍵是無符號整數。

語法

nodelist.keys();

引數

此方法不接受任何引數。

返回值

它返回一個迭代器。

HTML DOM NodeList ‘keys()’ 方法示例

以下示例說明了使用 keys() 方法獲取子節點及其鍵的實現。

獲取子節點

在以下示例中,我們建立了幾個元素,然後將它們附加到一個節點(父節點),然後使用 keys() 方法,我們獲得一個迭代器來獲取 NodeList 中的所有鍵。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist keys() Method</title>
</head>
<body>
    <p>Click to get the child nodes:</p>
    <button onclick="fun()">Click me</button>
    <p id="entry"></p>
    <script>
        function fun() {
            let x = document.getElementById("entry");
            let nodes = document.createElement("section");
            let nodeOne = document.createElement("h1");
            let nodeTwo = document.createElement("p");
            let nodeThree = document.createElement("h2");
            let nodeFour = document.createElement("table");
            nodes.appendChild(nodeOne);
            nodes.appendChild(nodeTwo);
            nodes.appendChild(nodeThree);
            nodes.appendChild(nodeFour);
            let elelist = nodes.childNodes;
            for (let i of elelist.keys()) {
                x.innerHTML += elelist[i].localName + "<br>";
            }
        };
    </script>
</body>
</html>

獲取子節點的鍵

以下示例返回所有子節點的鍵。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist keys() Method</title>
</head>
<body>
    <p>Click to get the keys of the child nodes:</p>
    <button onclick="fun()">Click me</button>
    <p id="keys"></p>
    <script>
        function fun() {
            let x = " ";
            let nodes = document.createElement("section");
            let nodeOne = document.createElement("h1");
            let nodeTwo = document.createElement("p");
            let nodeThree = document.createElement("h2");
            let nodeFour = document.createElement("table");
            nodes.appendChild(nodeOne);
            nodes.appendChild(nodeTwo);
            nodes.appendChild(nodeThree);
            nodes.appendChild(nodeFour);
            let elelist = nodes.childNodes;
            for (let i of elelist.keys()) {
                x += i + "<br>";
            }
            document.getElementById("keys").innerHTML = x
        };
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
keys() 是 51 是 16 是 50 是 10 是 38
廣告