javascript – MD5字符串无法正确显示html()

我有两个带有盐和密码的跨度

<div>
    $salt = '<span id="salt"></span>';<br />
    $password = '<span id="password"></span>';
</div>

然后我使用以下jQuery代码获取salt,将其添加用户输入的密码,并返回salt和散列密码(以复制到配置文件中)

salt = (Math.random() +1).toString(36).substr(2,16);
$('#salt').html(salt);
hashed = CryptoJS.MD5(salt + $(this).val());
$('#password').html(hashed);

代码使用salt ID将salt添加到span中,但它不会向密码ID添加任何内容.

如果我输入代码警报(哈希),它将打开一个md5值的警报.

如果我将.html()更改为.text(),它就可以了.

解决方法

CryptoJS.MD5()方法返回一个对象.要将此对象转换为字符串,请使用toString()方法.

hashed = CryptoJS.MD5(value);
var hashedString = hashed.toString();

而不是将文本插入元素使用jQuerys text()方法. jQuery html()方法用于设置元素innerHTML值.但是你想插入未转义的文字.

$('#password').text(hashedString);

如果一个对象传递给text(),它将自动调用它上面的toString(),尽管引用中没有记录

参考

.text(文字)

The text to set as the content of each matched element. When Number or Boolean is supplied,it will be converted to a String representation. […] be aware that this method escapes the string provided as necessary so that it will render correctly in HTML.

jQuery API Documentation: text()

.html(htmlString)

A string of HTML to set as the content of each matched element

jQuery API Documentation: html()开始

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...