尝试将元素添加到 Javascript 中的组会导致“...不是对象”。错误,即使元素是一个对象

Attempt to add an element to a group in Javascript causes "... not an object." error even though the element is an object

描述:尝试将元素添加到 javascript 组会导致 "TypeError: Argument 1 of Node.appendChild is not an object.",即使我已使用 typeof 验证它是一个对象。

let d = SVG('board').size(100, 100);

function createElem(elemId) {
  let elem;
  elem = d.rect().attr({
    id: elemId
  });
  return elem;
};

function main() {
  'use strict';
  let elem, elemId, s;

  elemId = `elem101`;
  elem = createElem(elemId);
  alert(elem); // Returns ‘elem101’ although elem is an object. --A
  s = d.group();
  s.add(elem); // Appears to work fine up to this point

  // However, replacing the previous line with the following
  // three lines of code causes an error
  elem = document.getElementById(elemId);
  alert(elem); // returns ‘[object SVGRectElemnt]’; Why? -- B
  // In A, the alert returns the element id of ‘elem101’
  // but here in B it returns the rectangle object.
  // Why this difference?
  try {
    s.add(elem); // Causes error: “TypeError: Argument 1 of
    // Node.appendChild is not an object.”
    // I am unable to add the element returned by getElementById
    // to the group.
  } catch (e) {
    console.log(e.message);
  }
};

main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.5/svg.js"></script>

<div id='board'></div>

向正文添加代码片段

看起来像 add expects an SVG.js object, not an DOM Node. You can get the SVG.js object from the DOM Node using the instance property

这是相同的代码段,现在使用 elem.instance,它不会引发错误。也就是说,它不会两次添加相同的元素,所以它做的不多...

如果想通过ID获取SVG.js对象,可以使用the SVG.get() method获取元素

let d = SVG('board').size(100, 100);

function createElem(elemId) {
  let elem;
  elem = d.rect().attr({
    id: elemId
  });
  return elem;
};

function main() {
  'use strict';
  let elem, elemId, s;

  elemId = `elem101`;
  elem = createElem(elemId);
  alert(elem);
  // Returns ‘elem101’ although elem is an object.
  // Apparently SVG.js overrides the toString() method of their objects to
  // return the id property if present.
  s = d.group();
  s.add(elem); // Appears to work fine up to this point

  elem = document.getElementById(elemId);
  alert(elem); // returns ‘[object SVGRectElemnt]’; Why? 
  // Since you're using DOM methods, it's retrieving a DOM object.
  // To get the SVG.js object, use an SVG.js method
  // elem = SVG.get(elemId);

  try {
    s.add(elem.instance); // does nothing because of the add() call above 
  } catch (e) {
    console.log(e.message);
  }
  // OR
  try {
    s.add(SVG.get(elemId)); // does nothing because of the add() call above
  } catch (e) {
    console.log(e.message);
  }
};

main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.5/svg.js"></script>

<div id='board'></div>