jquery's append not working with svg element?

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

Assuming this:



 
 

        
14条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 06:47

    When you pass a markup string into $, it's parsed as HTML using the browser's innerHTML property on a

    (or other suitable container for special cases like ). innerHTML can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that was supposed to be in the SVG namespace.

    innerHTML is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.

    HTML5 promises to let you use without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML even though they look like part of an HTML document.

    However, for today's browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:

    
    
    
        
        
    
    

    *: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML, then transfer it to the desired target. It'll likely be a bit slower though:

    
    

    **: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.

提交回复
热议问题