用JavaScript编码Alt属性 [英] Alt attribute encoding with JavaScript

查看:106
本文介绍了用JavaScript编码Alt属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Html实体必须编码 alt属性HTML页面中的图像。所以

 < img id =formulaalt =A& rarr; Bsrc =formula.png /> 

可以正常工作。



另一方面,相同的JavaScript代码将无法工作

  document.getElementById('formula')。alt ='A& rarr ; B; 

并产生 A& rarr; B 而不是 A→ B



如何通过JavaScript实现,当不可能将特殊(未编码)字符放入源代码中?

解决方案

如果您无法使用Unicode格式保存文件, $ p $函数decodeHTML(str){
return str.replace(/&#(\d +);?/ g,function(){
return String .fromCharCode(arguments [1])$ ​​b $ b});
}

但是,这要求您使用数字表示法。在这种情况下&#8594;


Html entities must be encoded in alt attribute of an image in HTML page. So

<img id="formula" alt="A &rarr; B" src="formula.png" />

will work well.

On the other hand, the same JavaScript code will not work

document.getElementById('formula').alt = 'A &rarr; B';

and will produce A &rarr; B instead of A → B.

How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?

解决方案

Here's an alternative if you can't save your file using a Unicode format:

function decodeHTML(str) {
    return str.replace(/&#(\d+);?/g, function() {
        return String.fromCharCode(arguments[1])
    });
}

However, this requires you to use the numeric representation. In this case &#8594;.

这篇关于用JavaScript编码Alt属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆