jquery's append not working with svg element?

后端 未结 14 2180
北海茫月
北海茫月 2020-11-21 06:28

Assuming this:



 
 

        
14条回答
  •  梦如初夏
    2020-11-21 07:01

     var svg; // if you have variable declared and not assigned value.
     // then you make a mistake by appending elements to that before creating element    
     svg.appendChild(document.createElement("g"));
     // at some point you assign to svg
     svg = document.createElementNS('http://www.w3.org/2000/svg', "svg")
     // then you put it in DOM
     document.getElementById("myDiv").appendChild(svg)
     // it wont render unless you manually change myDiv DOM with DevTools
    
    // to fix assign before you append
    var svg = createElement("svg", [
        ["version", "1.2"],
        ["xmlns:xlink", "http://www.w3.org/1999/xlink"],
        ["aria-labelledby", "title"],
        ["role", "img"],
        ["class", "graph"]
    ]);
    function createElement(tag, attributeArr) {
          // .createElementNS  NS is must! Does not draw without
          let elem = document.createElementNS('http://www.w3.org/2000/svg', tag);             
          attributeArr.forEach(element => elem.setAttribute(element[0], element[1]));
          return elem;
    }
    // extra:  for example requires attributes to render. Check if missing.
    

提交回复
热议问题