Why does <textarea> display <> instead of <>?

两盒软妹~` 提交于 2020-01-24 12:49:08

问题


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, and 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.


回答1:


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.



来源:https://stackoverflow.com/questions/7494189/why-does-textarea-display-instead-of-ltgt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!