Because jquery was not integrated at the beginning of the project, many methods were written natively. Today I went online to find several methods for manipulating class names, as follows:
export const hasClass = (el, cls) => {
return el.className.match(new RegExp('(\s|^)' + cls + '(\s|$)'))
}
export const removeClass = function (el, cls) {
if (hasClass(el, cls)) {
var reg = new RegExp('(\s|^)' + cls + '(\s|$)')
el.className = el.className.replace(reg, ' ')
}
}
export const addClass = function (el, cls) {
if (!this.hasClass(el, cls)) el.className += " " + cls
}
export const toggleClass = (el,cls) => {
console.log(hasClass)
if(hasClass(el,cls)){
removeClass(el, cls)
}else{
addClass(el, cls)
}
}
But when I use it, I always get an error, as follows:
Uncaught TypeError: Cannot read property 'hasClass' of undefined
at addClass (Route.js?7c64bfe…:27892)
at HTMLpElement.item.onclick (Route.js?7c64bfe…:139726)
I interrupted and debugged, but still couldn't find the cause of the problem. I wonder if any of you have encountered the same problem?
It is correct to call addClass and removeClass in toggleClass. Why do you remember adding this in front of hasClass?
It depends on what object this refers to in your this.hasClass(). You can check whether this refers to the global object