Reputation: 5479
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.
Upvotes: 2
Views: 530
Reputation: 71004
For the first function
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
The first line gets the object by its ID if Obj
is a string that is the ID of a DOM element. Otherwise it leaves the value of Obj
alone. This is using the "ternary conditional" operator, a? b: c
. which as a value of b
if a
is truthy and c
otherwise. Doing this allows the function to accept a string or a DOM element.
Obj.className=Obj.className==NameA?NameB:NameA;
The next line sets the CSS class of the DOM element from the last line to NameB
if the CSS class of the DOM element is NameA
and otherwise sets it to NameA
. 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 with NameA
.
function showMenu(iNo){
ExChgClsName("Menu_"+iNo,"MenuBox","MenuBox2");
}
The second function just applies the first to swap the CSS class of the the DOM element with ID of "Menu_"+iNo
between "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
var Obj = document.getElementById(Obj) || Obj;
That should be more efficient on all implementations and is surely more readable. It uses the ||
operator as a guard to assign Obj
back to itself if only if document.getElementById
returns null
.
Upvotes: 4
Reputation: 7512
function ExChgClsName(Obj,NameA,NameB){
//ternary operator, sets Obj = the dom object with id = 1st agrument if it exists
//you can get away with this because an object is "truthy" in javascript
// truthy meaning that if you try to evaluate it as a boolean it is the same as true
// if nothing is found getElementById returns null wich is the same as false
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
//ternary operator again. changes the class of the dom object to the 3rd argument
//if its class is already the 2nd argument
//otherwise it changes it to the second argument
Obj.className=Obj.className==NameA?NameB:NameA;
}
function showMenu(iNo){
//calls exChgCLsName with the specified arguments
ExChgClsName("Menu_"+iNo,"MenuBox","MenuBox2");
}
// Runs the showMenu function when clicked
<a href="javascript:showMenu(2);">
Upvotes: 0
Reputation: 48246
Exchange the cascading style sheet class name on an object from A to B
Find the element
if the object's css class name is nameA, set it to nameB, otherwise, set it to nameA
Upvotes: 0