javascript - Can't set innerHTML when using strings that start with '<'
问题描述
I have a textarea that will populate another section with what the user inputs and my code works fine as long as I dont type anything starting with "<". Whenever I have a string like "<anything else can follow" that starts with "<", it wont set the innerhtml.
var text = "<i wont print"
text = "i will print!"
trans_txt.innerHTML = text;
Is "<" some kind of override character for innerhtml? I was wondering if anyone knew what was happening and if there is a way I could change the text var into purely string without having to worry about my string not showing up.
edit: I realized this because the default textarea message is "<text area"
解决方案
<i
followed by a space is HTML syntax for "Start an <i>
(idiomatic/italic) tag" Since the parser doesn't see the end of the tag's definition (that is, a >
), everything between the <i
and the end is considered an error and dropped.
If you want to insert plain text only, use textContent
instead:
var text = "<i wont print"
document.body.textContent = text;
textContent
is also faster and safer. Only use innerHTML
when deliberately inserting HTML markup.
Don't use innerText
- best to prefer textContent
instead in almost all situations.
推荐阅读
- node.js - 增加内存限制 npm 包不适用于运行节点 npm 包
- development-environment - Outsystems - 添加另一个环境
- android - 发布版本无法连接到谷歌播放服务
- reactjs - React Axios:有时状态不传递 onClick 事件
- bash - 移动不包含特定字符串的文件
- android - 在 Android 上以编程方式启用多进程 WebView
- angular - Angular 路由守卫始终仅重定向到应用程序组件
- verilog - 如何正确处理零位宽情况?
- node.js - 如何创建一个 ID 是另一个模型的外键的模型
- c++ - 如何避免在 C++ 中调用两次析构函数?