【问题标题】:why can't I set an ascii reference in an img title attribute using js?为什么我不能使用 js 在 img 标题属性中设置 ascii 引用?
【发布时间】:2011-05-04 22:17:18
【问题描述】:

我在图片标题中使用 ascii 字符引用 (®) 时遇到问题。当您通过 html 正文设置它时它工作正常,但是当尝试通过 javascript 做同样的事情时不起作用。

检查 sscce:

<style type="text/css">body {background-color:black;}</style>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<p>this image has the correct ascii character title:<br /><img src="http://www.prototypejs.org/images/logo-home.gif" id="img1" title="&reg;" /></p>
<p>but why can't I set the same value via javascript?<br /><img src="http://www.prototypejs.org/images/logo-home.gif" id="img2" /></p>
<script type="text/javascript">
$("img2").title = "&reg;";
</script>

谢谢。

【问题讨论】:

  • 啊,我想我明白了.. 任何地方都有“htmlToText”实用功能吗?我不想必须以编程方式创建一个 html 元素只是为了提取文本......

标签: javascript html ascii


【解决方案1】:

$("img2").title = "®" 如果不使用应该可以工作

$("img2").title ='\u00AE'.

html 实体不会被翻译成纯文本。

【讨论】:

    【解决方案2】:

    http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/有很多答案

    但它的基本要点是您设置节点的文本而不是 html,因此没有 html 实体。

    但是,您可以设置隐藏对象的 innerHTML 并读取该对象的文本值。或者假设您的源编码允许它直接输入 reg 符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2022-11-20
      相关资源
      最近更新 更多