前几天在维护使用原生JS实现博客,添加一个以markdown格式展示博文的功能。
好不容易让md插件在页面中生效了,发现转化md文档时报错。
报错的时机是:点开某一篇文章的详情预览,就会弹出右侧错误。
jquery.min.js:2 Uncaught (in promise) TypeError: X[g].exec is not a function
at fb.tokenize (jquery.min.js:2)
at fb.compile (jquery.min.js:2)
at fb.select (jquery.min.js:2)
at fb (jquery.min.js:2)
at Function.fb.matches (jquery.min.js:2)
at Function.m.filter (jquery.min.js:2)
at m.fn.init.m.fn.<computed> [as children] (jquery.min.js:2)
at Function.editormd.markdownToCRenderer (editormd.js:3730)
at Function.editormd.markdownToHTML (editormd.js:3983)
at Object.md2Html (util.js:53)
我排查了一段时间,发现是我在 Object 的原型上追加了我的一些公用方法,导致报错,网上说可能是jquery对 Object 的原型有限制,恰巧我这个markdown插件用的就是jquery的框架。
——————util.js——————
(function (glo, undefined) {
Object.prototype.isReceived = (ajax) =>
ajax.readyState === 4 && ajax.status < 300 && ajax.status !== 0;
Object.prototype.isEmptyObject = (obj) => {
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
Object.prototype.str2Html = (str) => {
let box = document.createElement('div');
box.innerHTML = str;
return box.lastElementChild;
//修复bug:lastChile有可能是文本对象
}
/* content转markdown界面
参数1: 放转化的md文本
参数2: textarea id
参数3: 外部div id(不加 #)
*/
Object.prototype.md2Html = (content, taId, divId) => {
document.querySelector(taId).textContent = content;
editormd.markdownToHTML(divId);
}
Object.prototype.formatDate = (time) => {
const dateTime = new Date(time);
const year = dateTime.getFullYear();
const month = dateTime.getMonth() + 1;
const date = dateTime.getDate();
const hour = dateTime.getHours();
const minute = dateTime.getMinutes();
const second = dateTime.getSeconds();
return `${year}年${month}月${date}日 ${add0(hour)}:${add0(minute)}:${add0(second)}`;
}
function add0(s) {
return s < 10 ? '0' + s : s;
}
glo.util = util;
})(window);
我考虑了一下,直接把util的结构改成返回一个对象,这个对象中包含着我若干工具方法。
(function (w) {
let util = {
isReceived: (ajax) =>
ajax.readyState === 4 && ajax.status < 300 && ajax.status !== 0,
isEmptyObject: (obj) => {
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
},
str2Html: (str) => {
let box = document.createElement('div');
box.innerHTML = str;
return box.lastElementChild;
//修复bug:lastChile有可能是文本对象
},
formatDate: (time) => {
const dateTime = new Date(time);
const year = dateTime.getFullYear();
const month = dateTime.getMonth() + 1;
const date = dateTime.getDate();
const hour = dateTime.getHours();
const minute = dateTime.getMinutes();
const second = dateTime.getSeconds();
return `${year}年${month}月${date}日 ${add0(hour)}:${add0(minute)}:${add0(second)}`;
},
getCurrRootUrl: () => {
return pattern_forRoot.exec(w.location.href)[0];
},
tagFilter: (str) => {
return str
.replace(/&/g, '&')
.replace(/ /g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
};
function add0(s) {
return s < 10 ? '0' + s : s;
}
w.util = util;
})(window);
现在就不会报错了。