gpt4 book ai didi

javascript - 尝试在 Javascript 中将元素添加到组中会导致 "... not an object."错误,即使该元素是对象

转载 作者:行者123 更新时间:2023-12-02 22:50:04 25 4
gpt4 key购买 nike

描述:尝试将元素添加到 javascript 组会导致“TypeError:Node.appendChild 的参数 1 不是对象”。即使我已经使用 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需要一个 SVG.js 对象,而不是 DOM 节点。您可以使用 the instance property 从 DOM 节点获取 SVG.js 对象.

这是相同的代码片段,现在使用 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>

关于javascript - 尝试在 Javascript 中将元素添加到组中会导致 "... not an object."错误,即使该元素是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com