Why does <textarea> display <> instead of <>?
Shouldn't a browser's textarea display raw text? Look at the following snaps from this post, and pay attention to the <script>
tag:
1- We can see the angled brackets around the script word:
2- Now look at the source of the page. We can see the angled brackets are represented by their HTML entities:
3- Click to edit the post and you'll see that the angled brackets are visible in the textarea--NOT their HTML entities:
4- Look at the XHR response from the server (when we clicked edit), we can see the HTML entities and NOT the angled brackets we see in the textarea:
How is it possible that the textarea--when editing the post--displays the angled brackets and not their HTML entities? Shouldn't textareas display raw text? I tried this on my site, a开发者_如何学Cnd the textarea shows the HTML entities, and not brackets, with identical source code.
The post page also shows the angled brackets even when they are inside code
and pre
tags. Shouldn't they be output as raw text too? I also tried this on my site, and the page shows the HTML entities, and not the angled brackets.
What I am missing here?
I'm asking because struggling with implementing a feature on my site. I want to show people the encoded entities when they go to edit something, but I want to store a raw version. SO seems to have done, but I have no idea how.
See Character Data and Markup and consider CDATA sections in HTML (take a peek at the DTD although do note it is insufficient to entirely describe HTML).
The script
(and style
) elements have such a CDATA designation while textarea
does not. Store the data as it ("unescaped") but make sure to HTML-encoded outside of CDATA sections in the HTML (and even inside, take care to guard against terminators like </anything
-- the <
and /
characters must be separated to be entirely legal in HTML). See CDATA vs PCDATA for some more details.
Happy coding.
精彩评论