Correct function:
function addClass(element,value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName += " ";
newClassName += value;
element.className = newClassName;
}
}
Is it okay to write it like this?
function addClass(element,value) {
if(!element.className) {
element.className = value;
} else {
newClassName += " ";
newClassName += value;
}
element.classList.add() is more convenient
If you want to be compatible with IE10 or below, then I have nothing to say
is equivalent to
There is a compatibility issue
Equivalent to the above, solving compatibility issues
Other packaging methods
The answer is definitely not possible
What this needs to be implemented is to add a class to the dom element.
else
In the branch, you only operate a string. What is the use if it is not set to the dom element in the end? For the added class to take effect, it must be placed on the dom elementIn addition, there is also a problem with your correct writing:
In fact
else
branching can be simplifiedCan’t. The purpose of the function is to give
element
加上一个叫value
的类,你else
里面根本没有对element.className
进行赋值怎么行,那个newClassName
只是个变量,用来保存现有class
,并加上value
这个新class
后,塞回element.className
, soFirst:
is followed by:
In fact, the original function has a better way of writing.
else
There is no need to get a variable in it, just spell it directly:No, it’s not possible. NewClass must be assigned first after the else statement before the operation can be reassigned to element.className. If it is removed, it seems that there is no such function
I just saw it wrong...
No way