简体   繁体   中英

How do I replace an SVG element

I have a svg document - map of the world, which resides in its own file. I am getting some data from the database which I then loop thru add xlink to the appropriate countries which are appended to the end of the document. However when this happens, the appended xlinks are drawn over other nodes. For example the country of South Africa has Lesotho within its boundaries. South Africa gets a link and then ends up covering Lesotho. How do I make sure Lesotho is accessible or redrawn after the link is created? This is the code I am using.

window.onload = function() {
  // Get the Object by ID
  var a = document.getElementById("SVGWorldMap");
  // Get the SVG document inside the Object tag
  var svgDoc = a.contentDocument;
  // Get one of the SVG items by ID;
  var svgItem = svgDoc.getElementById("ocean");
  // Set the colour to something else
  svgItem.style.fill = "#5593BB";
  for (let i = 0; i < Countries.Countries.length; i++) {
    var x = svgDoc.getElementById(Countries.Countries[i].locCountry.toLowerCase());
    var link = svgDoc.createElementNS("http://www.w3.org/2000/svg", "a");
    link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "../Scripts/prodList.aspx?idLocation=" + Countries.Countries[i].idLocation);
    link.setAttribute('target', '_top');
    svgDoc.documentElement.appendChild(link);
    x.style.fill = "#123456";
    x.addEventListener('mouseover', mouseOverEffect);
    x.addEventListener('mouseout', mouseOutEffect);
    link.appendChild(x);
    //console.log(Countries.Countries[i].locCountry.toLowerCase());
  }
};

Try preserving the order of the elements by replacing each one with a link instead of adding links to the end in Countries.Countries order (assuming the links and paths(?) share a parent).

So instead of this:

svgDoc.documentElement.appendChild(link);

do this:

x.parentNode.replaceChild(link, x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM