双层for循环内打印SVG圆形ID返回null或[object SVGCircleElement]问题
问题原因及修复方案
核心错误点
- 计数器
c无规律重复自增:为圆形设置id、name,为矩形设置id、name,查询ID时你总共执行了5次c++,导致你要查询的id和实际生成的id完全不匹配,自然返回null - DOM查询语法错误:
document.getElementById()只接收纯ID字符串参数,你传入了jQuery选择器对象属于传参错误;querySelector()查询ID元素需要加#前缀,否则会按标签名查询,自然找不到元素 - 冗余查询:你创建圆形时已经将元素实例存在了
circle变量中,完全不需要再通过ID查询DOM获取元素
修正后可运行代码
const width = document.getElementById("svg239462").viewBox.baseVal.width; const height = document.getElementById("svg239462").viewBox.baseVal.height; console.log("this is width " + width); console.log("this is height " + height); var draw = Snap('#svg'); var c = 0; var count = 0; let size = Math.round(0.02 * width); for (let i = 0; i <= width; i = i + size) { count++; for (let j = 0; j <= height; j = j + size) { var rect = draw.rect(i, j, size, size); let circle = draw.circle(i, j, 30); // 给每个元素分配唯一ID,避免重复自增c const circleId = "circle_" + c; c++; const rectId = "rect_" + c; c++; circle.attr({ fill: "#b905fa", "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: circleId, name: "circle" + circleId.split('_')[1] }); rect.attr({ fill: "#d00bf3", "fill-opacity": 0.1, stroke: "#000", "stroke-width": "1px", id: rectId, name: "rect" + rectId.split('_')[1] }); // 直接用已有的circle变量,无需重复查询DOM console.log("this is ID for circle: " + circleId); console.log('Point at 50,50:', circle.isPointInFill(new DOMPoint(50, 50))); } } // 后续如果要单独查询元素,注意语法规范 const circleID = document.getElementById("circle_0"); console.log("this is ID for circle: " + circleID); // querySelector查询ID需要加#前缀 const selectedElement = document.querySelector('#circle_0'); console.log('.id', selectedElement.id); console.log("this is for rectangle count: " + count); if ($("#rect908").height() < $('#d_electrolyzer').height()) { console.log("alert"); $("#rect908").attr({ fill: "#000", "fill-opacity": 1 }); } else { console.log("alert2"); }
内容的提问来源于stack exchange,提问作者Arif Ahmed
相关产品推荐
相关产品推荐

