[英]Uncaught TypeError when using .replace() on HTML5 data attribute storing numbers retrieved with jQuery $.data()
I am storing database values in HTML5 data attributes via jQuery while first escaping them to be HTML attribute safe, and it works fine with String
s. 我正在通过jQuery将数据库值存储在HTML5数据属性中,同时首先将它们转义为HTML属性安全,并且可以与
String
一起使用。
However, if I've stored a number that doesn't begin with 0
, it always gives, for example when the value is 1000
: 但是,如果我存储的数字不是以
0
开头,则它总是给出,例如当值是1000
:
Uncaught TypeError: Object 1000 has no method 'replace'
未捕获的TypeError:对象1000没有方法“替换”
How can this be fixed? 如何解决?
html escaper/unescaper htmlscaper / unescaper
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function unescapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
}
I $.append()
the element with a String
with this data-sortValue="'+sortValue+'"
as the HTML5 data. 我
$.append()
带有String
的元素,并将此data-sortValue="'+sortValue+'"
作为HTML5数据。
I try to read it again in another function with unescapeHtml(String($(this).data('sortvalue')))
. 我尝试使用
unescapeHtml(String($(this).data('sortvalue')))
在另一个函数中再次读取它。
The problem is you are not handling the case where unsafe
could be undefined
or unsafe
is a number/boolean. 问题是您没有处理
unsafe
可能是undefined
或unsafe
是数字/布尔值的情况。
Here we can check whether unsafe
exists and replace
function is available. 在这里,我们可以检查是否存在
unsafe
,并且可以使用replace
功能。
function escapeHtml(unsafe) {
return unsafe && $.isFunction(unsafe.replace) ? unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'") : unsafe;
}
function unescapeHtml(unsafe) {
return unsafe && $.isFunction(unsafe.replace) ? unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'") : unsafe;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.