使用 JavaScript 选择 SVG 和路径元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7522805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting SVG and path elements with JavaScript
提问by tuddy
I would like to select the last path in an SVG and remove it. I've tried a variety of methods, in pure javascript and in jquery and I don't seem to be able to access the SVG properly or its paths.
我想选择 SVG 中的最后一条路径并将其删除。我尝试了各种方法,在纯 javascript 和 jquery 中,我似乎无法正确访问 SVG 或其路径。
HTML:
HTML:
<div id="thesvgwrapper">
<svg id="thesvg"...><path ....></path><path ...></svg>
</div>
I CAN clear the SVG using:
我可以使用以下方法清除 SVG:
$('svg#thesvg').empty();
I CAN see the SVG's contents using:
我可以使用以下方法查看 SVG 的内容:
var svgwrapper = $('#svgwrapper');
var svgcontents = $(svgwrapper).html();
alert(svgcontents);
However, I CANNOT similarly select the SVG and see it's path contents...
但是,我不能类似地选择 SVG 并查看它的路径内容...
my goal is something like
我的目标是这样的
$('#thesvg path:last').remove();
thanks a million for any help
感谢一百万的帮助
回答by Cameron Laird
Here's executable code in pure JavaScript:
这是纯 JavaScript 中的可执行代码:
var paths = svgDoc.getElementsByTagName("path");
var last_path = paths[paths.length - 1];
last_path.parentNode.removeChild(last_path);
回答by Dave F
I'm assuming that you're using an SVG compatible browser, such as Firefox.
我假设您使用的是兼容 SVG 的浏览器,例如 Firefox。
It's been a while since I tried to manipulate SVG via jQuery. I remember that I was reluctant to use an SVG jQuery plugin, but without one I was having some problems accessing the elements in the DOM. Including the jQuery SVGplugin allowed me to access the elements so including it might help with the problems that you're having.
自从我尝试通过 jQuery 操作 SVG 已经有一段时间了。我记得我不太愿意使用 SVG jQuery 插件,但是如果没有,我在访问 DOM 中的元素时遇到了一些问题。包含jQuery SVG插件允许我访问元素,因此包含它可能有助于解决您遇到的问题。