如何使用jQuery在mxGraph中插入<image>标签避免自动转为<img>?
解决mxGraph中插入
标签被转为
的问题
问题出在jQuery的append()方法默认以HTML上下文解析内容,而在HTML规范里<image>是<img>的别名,所以会被自动转换。要保留XML格式的<image>标签,得用XML DOM的方式创建和插入元素,具体有两种方案:
方案一:用原生DOM的命名空间创建元素
mxGraph的图形基于SVG(属于XML),需要使用带命名空间的方法创建<image>元素:
// 获取父元素的原生DOM对象 const parentEl = $(this).parent()[0]; // 创建SVG命名空间下的image元素 const imageEl = document.createElementNS('http://www.w3.org/2000/svg', 'image'); // 设置元素属性 imageEl.setAttribute('class', 'rep'); // xlink:href需要指定xlink命名空间 imageEl.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', src); imageEl.setAttribute('width', '25px'); imageEl.setAttribute('height', '25px'); // 将元素插入父节点 parentEl.appendChild(imageEl);
方案二:用jQuery的parseXML解析XML字符串
先把标签当作XML解析,再插入到DOM中:
// 构建XML格式的标签字符串 const xmlStr = `<image class="rep" xlink:href="${src}" width="25px" height="25px" />`; // 解析XML得到文档对象 const xmlDoc = $.parseXML(xmlStr); // 提取image元素 const imageEl = xmlDoc.querySelector('image'); // 插入到父元素中 $(this).parent().append(imageEl);
这两种方式都能避免jQuery把<image>转换成<img>,满足XML识别的需求。
内容的提问来源于stack exchange,提问作者muhammad Yousaf
相关产品推荐
相关产品推荐

