如果变量 sPoints 字符串的格式不正确(例如,点由“;”分隔),则不会绘制多边形,并且在调试器中我可以看到检测到错误。然而,没有抛出可以捕获的异常。 如果满足以下条件,则工作正常:
var sPoints = "310,320 400,320 379,358";
但如果出现以下情况,则会“出错”:
var sPoints = "310,320;400,320;379,358";
try {
var NewPoly = document.createElementNS(svgns, "polygon");
NewPoly.setAttributeNS(null, 'id', "someId");
NewPoly.setAttributeNS(null, 'points', sPoints);
NewPoly.setAttributeNS(null, 'class', myClass);
NewPoly.setAttributeNS(null, 'onclick', "handlePgonClick(evt)");
objSvgElem.appendChild(NewPoly);
}
catch (err) {
vShowMsg("drawing shape failure: " + err.message);
}
最佳答案
您可以计算 SVG DOM 已接受多少分,并将其与您认为应该获得的数字进行比较。
var NewPoly = document.createElementNS('http://www.w3.org/2000/svg', "polygon");
NewPoly.setAttribute('points', "310,320;400,320;379,358");
alert(NewPoly.points.numberOfItems);
NewPoly.setAttribute('points', "310,320 400,320 379,358");
alert(NewPoly.points.numberOfItems);
关于javascript - 如何在 JavaScript 中使用 setAttributeNS() 捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852005/