使用setAttributeNS修改SVG Path Arc元素失败及eXist存储咨询
SVG路径不显示问题修复与eXist数据库存储方案
错误点排查
你的代码里有三处关键错误导致SVG路径没显示:
- 获取SVG元素的方式错误:你用了
SVG.getElementById,但SVG不是全局可用对象,应该用已经获取到的SVG_Def变量调用getElementById。 setAttributeNS使用完全错误:- 这是方法而非属性,不能用
=赋值,必须以函数调用形式element.setAttributeNS(...)执行。 d和style属性属于SVG自身命名空间,不需要用xlink命名空间,正确命名空间可传null或SVG官方命名空间http://www.w3.org/2000/svg。- 属性名和属性值里的多余单引号要去掉,比如
"'d'"和"'M ...'"里的单引号会导致浏览器识别无效属性,进而让样式和路径失效。
- 这是方法而非属性,不能用
修正后的JavaScript代码
function Setup2() { var SVG_Def; var Bezier_Curve_Identification; // 把路径和样式存入变量,方便后续存储到数据库 var pathData = "M 300, 200 A 20, 20 0,0,1 340,200"; var pathStyle = "stroke: blue; stroke-width: 3; fill: none;"; document.getElementById("My_Text").value = "I'm right here."; SVG_Def = document.getElementById("My_SVG"); Bezier_Curve_Identification = SVG_Def.getElementById('Bezier_Curve_1'); // 正确设置d属性(无需命名空间,传null) Bezier_Curve_Identification.setAttributeNS(null, "d", pathData); // 设置style属性,也可直接用setAttribute Bezier_Curve_Identification.setAttribute("style", pathStyle); // 调用存储到eXist的函数 saveToExist(pathData); } // 示例:将路径数据发送到eXist数据库的XQuery接口 function saveToExist(pathData) { // 请根据实际情况修改eXist的XQuery端点路径 fetch("/exist/rest/db/apps/HTML_Student/save-path.xq", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "pathData=" + encodeURIComponent(pathData) }) .then(response => response.text()) .then(result => { console.log("存储成功:", result); document.getElementById("My_Paragraph").textContent = "路径数据已存储到数据库"; }) .catch(error => { console.error("存储失败:", error); document.getElementById("My_Paragraph").textContent = "存储失败,请检查"; }); }
对应的XQuery示例(save-path.xq)
需要在eXist中创建该脚本,用于接收前端传参并存储路径数据:
xquery version "3.1"; declare namespace request="http://exist-db.org/xquery/request"; let $pathData := request:get-parameter("pathData", "") let $storagePath := "/db/apps/HTML_Student/path-data.xml" return if ($pathData ne "") then ( if (doc-available($storagePath)) then update insert <path>{$pathData}</path> into doc($storagePath)/paths else xmldb:store("/db/apps/HTML_Student", "path-data.xml", <paths><path>{$pathData}</path></paths>), "路径数据已成功存储" ) else "未接收到有效路径数据"
说明
- 把路径数据存入
pathData变量后,可灵活发送到eXist接口,上述示例用了POST表单方式,也可改用JSON格式传输。 - 需确保eXist权限设置正确,允许前端脚本访问对应XQuery端点和存储路径。
内容的提问来源于stack exchange,提问作者Speedlearner
相关产品推荐
相关产品推荐

