问题
When I use innerHTML from javascript, the browser (Safari and Firefox at least) seem to replace certain characters and numeric entities with their named entities.
The character \xa0 (non breaking space) gets replaced by ,
< (lesser than) gets replaced by <. But for example the umlaut ü is not replaced with ü.
I have not found any documentation for this behaviour.
A simple demo:
<h2 id="withoutnbsp">This does not use en be es pe (uses the \xa0 character)</h2>
<script>alert(document.getElementById("withoutnbsp").innerHTML);</script>
A more elaborate demonstration can be found here:
http://gist.github.com/89434
You can use the "raw" link on the gist page, to view it in your browser.
I need to know exactly which characters innerHTML replaces. Any help is appreciated. Thanks.
回答1:
The HTML 5 spec has rules for serializing an HTML fragment when you call innerHTML on it, documented here: Serializing HTML fragments (note that innerHTML isn't in the HTML 4 spec, so the HTML 5 spec is the current reference).
TLDR version of the spec: Spaces, angle brackets, ampersands, equals signs and double quotes are the only chars that get escaped when innerHTML is called.
回答2:
It's probably replacing them with HTML character entities, as per the HTML spec.
来源:https://stackoverflow.com/questions/711720/are-there-any-rules-regarding-special-characters-entities-and-innerhtml