function ExChgClsName(Obj,NameA,NameB){
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
Obj.className=Obj.className==NameA?NameB:NameA;
}
<a href="javascript:showMenu(2);">
i am a newbie of the js. so can’t understand the above two function very well. expect someone can explain the line’s meaning to me one by one. many thanks.
For the first function
The first line gets the object by its ID if
Objis a string that is the ID of a DOM element. Otherwise it leaves the value ofObjalone. This is using the “ternary conditional” operator,a? b: c. which as a value ofbifais truthy andcotherwise. Doing this allows the function to accept a string or a DOM element.The next line sets the CSS class of the DOM element from the last line to
NameBif the CSS class of the DOM element isNameAand otherwise sets it toNameA. This would have the effect of swapping out the classes so long as another class is never assigned to the element. If another class is assigned to the element, then it will start the cycle again withNameA.The second function just applies the first to swap the CSS class of the the DOM element with ID of
"Menu_"+iNobetween “MenuBox” and “MenuBox2”.Personally, I don’t like the first line of the first function because it does two searches of the DOM when it only needs to do one. I would do this
That should be more efficient on all implementations and is surely more readable. It uses the
||operator as a guard to assignObjback to itself if only ifdocument.getElementByIdreturnsnull.