简体   繁体   English

在HTML5数据属性上使用.replace()并存储用jQuery $ .data()检索到的数字时,出现未捕获的TypeError

[英]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, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
function unescapeHtml(unsafe) {
    return unsafe
        .replace(/&amp;/g, "&")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&quot;/g, "\"")
        .replace(/&#039;/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可能是undefinedunsafe是数字/布尔值的情况。

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, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;") : unsafe;
}
function unescapeHtml(unsafe) {
    return unsafe && $.isFunction(unsafe.replace) ? unsafe
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, "\"")
    .replace(/&#039;/g, "'") : unsafe;
}

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM