简体   繁体   English

尝试通过innerHTML理解此JavaScript行为

[英]Trying to understand this JavaScript behavior with innerHTML

I'm trying to set the less-than symbol and the less-than or equal symbol using innerHTML , then get the encoded text back out, not the decoded symbols. 我正在尝试使用innerHTML设置小于符号和小于或等于符号,然后取回编码的文本,而不是解码的符号。

This works with < < , but not with ≤ ,但不能与≤ . Is there a reason why this would be? 有什么理由吗?

var lt = '<';
var le = '≤';

var div_lt = document.createElement('div');
div_lt.setAttribute('original_value', lt);
div_lt.innerHTML = lt;

var div_le = document.createElement('div');
div_le.setAttribute('original_value', le);
div_le.innerHTML = le;

console.log([div_lt.innerHTML, div_lt.innerText, div_lt.getAttribute('original_value')]);
// gives [ "&lt;", "<", "&lt;" ], as I expected
console.log([div_le.innerHTML, div_le.innerText, div_le.getAttribute('original_value')]);
// gives [ "≤", "≤", "&le;" ], but the first value should be "&le;"

JSFiddle: https://jsfiddle.net/54m6c8sk/ JSFiddle: https ://jsfiddle.net/54m6c8sk/

In HTML < means "Start of tag" and means "≤". 在HTML中, <表示“标记开始”,而表示“≤”。

When you want to express < in HTML then you often must use an entity. 当您想用HTML表示< ,通常必须使用一个实体。 When you want to express , you never have to use an entity. 当你想表达 ,你永远不会用到的实体。

Converting DOM to HTML via innerHTML doesn't convert to &le; 通过innerHTML将DOM转换为HTML不会将转换为&le; because it is never useful to do so. 因为这样做永远没有用。

This is a fun one... but already answered: How do I prevent HTML encoding of '&' characters while copying content from a div to the title of the page? 这很有趣...但是已经回答了: 在将内容从div复制到页面标题时,如何防止'&'字符的HTML编码?

tldr: use textContent instead of innerHTML -- innerHTML is actually not part of the DOM spec tldr:使用textContent而不是innerHTML - innerHTML实际上不是DOM规范的一部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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