gpt4 book ai didi

javascript - 使用 getAttribute 从 javascript 中的 [object SVGCircleElement] 检索值

转载 作者:行者123 更新时间:2023-12-01 00:56:20 24 4
gpt4 key购买 nike

我在 JavaScript 函数中检索到了值“[object SVGCircleElement]”,并希望将其解压以获取更多信息,例如其 ID。它来 self 抄袭的一个普通的可拖动函数,并不认为这里完全需要它,重点是在 endDrag (mouseup) 事件上我有一个包含变量 [object SVGCircleElement] 的函数

function endDrag(evt){
alert(selectedElement);
selectedElement = false;
}

这给了我[object SVGCircleElement]例如,我如何获取其 ID?谢谢

另外 - [对象 SVGSVGElement]。当鼠标单击可拖动元素时,该对​​象将传递给该函数。 dom 中拖动的元素具有 ID 和 cy、cx 和 fill 等值,我也想检索这些值。

编辑-感谢下面的答案,我能够通过使用变量 selectedElement 和

获取有关 [object SVGCircleElement] 的信息
selectedElement.id gets ID
selectedElement.getAttribute("cx")`enter code here` gets the cx (as this is a svg circle)

等等

最佳答案

这个字符串只是实际js对象的字符串化。

您可以通过使用 console.log() 而不是 alert() 来看到它。

该对象将公开许多属性,这里无法列出所有属性。但对于 id,您只需访问其 .id 属性即可。

但是请注意,对于 SVGElement,某些属性实际上是 SVGAnimatedStrings您需要从中访问其 .baseVal 属性,或者您可能只想调用 Element.getAttribute() .

const selectedElement = document.querySelector('circle');

console.log('toString', selectedElement.toString());

console.log('.id', selectedElement.id);
console.log('.cx', selectedElement.cx);
console.log('.getAttribute("cx")', selectedElement.getAttribute("cx"));
<svg viewBox="0 0 100 100">
<circle id="my-circle" cx="50" cy="50" r="50"/>
</svg>

关于javascript - 使用 getAttribute 从 javascript 中的 [object SVGCircleElement] 检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554123/

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