【问题标题】:jQuery - escaping inline styles with HTML entitiesjQuery - 使用 HTML 实体转义内联样式
【发布时间】:2015-10-18 08:44:27
【问题描述】:

在尝试将 Javascript 编辑器 (CKEditor) 编辑的 HTML 插入某个 div 时,我遇到了一个奇怪的问题。在要插入的 HTML 中,双引号被 HTML 实体“替换”。效果很好。

除非“”以内联样式出现 - 然后 jQuery 删除整个内联样式。

我不希望它们被删除。如果可能的话,我更喜欢保留 HTML 实体。问题是为什么会发生这种情况?有什么解决方法吗?

在下面的示例中,我插入了一个文本,该文本应使用常规引号和 HTML 实体转义引号以内联样式使跨度变为红色。

第一行 (div1) 使 span 变为红色,div2 根本不是红色。

   window.onload = function() {
 $('#div1').html('<span style="color:red;">This text "here" is red</span>, while this is not.' );
 $('#div2').html('<span style=&quot;color:red;&quot;>This text &quot;here&quot; is red</span>, while this is not.' ); }

See JSFiddle/L7cq2pfd here

【问题讨论】:

  • div2 样式无效style=&amp;quot;color:red;&amp;quot; 你是怎么得到这个样式的?
  • CKEditor 会自动执行此操作,它会在您编辑时添加内联样式。这是为了帮助避免包含引号的文本出现问题,但在这种情况下会产生问题。

标签: javascript jquery html


【解决方案1】:

jQuery 将其插入为 style="&amp;quot;color:red;&amp;quot;" - 将 &amp;quot; 转换为 "replace(/&amp;quot;/g, '"') 在插入为 HTML 之前:

$('#div2').html('<span style=&quot;color:red;&quot;>This text &quot;here&quot; is red</span>, while this is not.'.replace(/&quot;/g, '"') ); 

http://jsfiddle.net/kb709s27/

为什么&amp;quot;" 的自动呈现是浏览器功能,而不是 JavaScript 功能。 jQuery 似乎会解析插入的 HTML 并尝试纠正格式错误的属性。如果你插入

$('#div2').html('<span style=color:red>');

然后 jQuery 更正此问题并插入 &lt;span style="color:red"&gt;。在您的情况下,jQuery 只看到格式错误的属性,因此尝试更正它,将 &amp;quot;color:red;&amp;quot; 包装到引号中。

【讨论】:

  • 谢谢 - 这很清楚,是我需要的。我错过了自动 HTML 呈现不是 Javascript 功能。
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 2013-07-30
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
相关资源
最近更新 更多