代码之家  ›  专栏  ›  技术社区  ›  smpa01

检索子项添加到要点

  •  1
  • smpa01  · 技术社区  · 1 年前

    有没有一种方法可以只检索添加到特定点的子对象。例如,我创建了 rect and circle 我正在执行 fnTwo 在我添加之前 path 希望它只会回来 矩形和圆形 。但它返回了所有的孩子;例如 rect, circle +path ; 即使在后面添加了路径。有没有办法让我执行 fnTwo 把孩子们加到那个时间点上。

    const svg = document.querySelector('svg');
    const svgns = "http://www.w3.org/2000/svg"
    const element = ['rect', 'circle'];
    
    //fn for append
    const fnOne = (element) => {
        const child = document.createElementNS(svgns, element);
        svg.append(child);
    
    }
    //append all elements
    for (const elements of element) {
        const element = elements;
        fnOne(element)
    };
    // get all the children elements **up to this point in time**
    const fnTwo = (element) => {
        const children = element.children;
      //do something with the children
        console.log(children); //brings all children added before + after
    }
    
    const children = fnTwo(svg);
    //add a path to test if it is retrieved through fnTwo
    const childThree = document.createElementNS(svgns, 'path');
    svg.append(childThree);
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Document</title>
      </head>
      <script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
      <body>
        <svg>      
        </svg>
      </body>
    </html>
    1 回复  |  直到 1 年前
        1
  •  2
  •   vanowm    1 年前

    您遇到的问题是,因为您返回了子级的原始“数组”,所以您需要做的是返回一个副本:

    const svg = document.querySelector('svg');
    const svgns = "http://www.w3.org/2000/svg"
    const element = ['rect', 'circle'];
    
    //fn for append
    const fnOne = (element) => {
        const child = document.createElementNS(svgns, element);
        svg.append(child);
    
    }
    //append all elements
    for (const elements of element) {
        const element = elements;
        fnOne(element)
    };
    // get all the children elements **up to this point in time**
    const fnTwo = (element) => {
        const children = [...element.children]; //shallow copy of the array
      //do something with the children
        console.log(children); //brings all children added before + after
    }
    
    const children = fnTwo(svg);
    //add a path to test if it is retrieved through fnTwo
    const childThree = document.createElementNS(svgns, 'path');
    svg.append(childThree);
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Document</title>
      </head>
      <script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
      <body>
        <svg>      
        </svg>
      </body>
    </html>