[英]what's the meaning of the functions in javascript?
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);">
我是js的新手。 因此無法很好地理解以上兩個功能。 希望有人可以一一向我解釋這句話的意思。 非常感謝。
對於第一個功能
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
如果Obj
是一個字符串,它是DOM元素的ID,則第一行通過其ID獲取對象。 否則,它會獨自留下Obj
的值。 這是使用“三進制條件”運算符a? b: c
a? b: c
。 如果a
為真,則為b
的值,否則為c
。 這樣做允許函數接受字符串或DOM元素。
Obj.className=Obj.className==NameA?NameB:NameA;
下一行設置CSS類從最后一行的DOM元素的NameB
如果CSS類的DOM元素是NameA
否則將其設置為NameA
。 只要從未將另一個類分配給該元素,這將具有換出這些類的效果。 如果另一個類被分配給該元素,那么它會再次開始循環NameA
。
function showMenu(iNo){
ExChgClsName("Menu_"+iNo,"MenuBox","MenuBox2");
}
第二個函數僅應用第一個函數, "Menu_"+iNo
在“ MenuBox”和“ MenuBox2”之間交換ID為"Menu_"+iNo
的DOM元素的CSS類。
我個人不喜歡第一個函數的第一行,因為當它只需要執行一次時,它將對DOM進行兩次搜索。 我會這樣做
var Obj = document.getElementById(Obj) || Obj;
這在所有實現上都應該更有效,並且更容易理解。 它使用||
僅當document.getElementById
返回null
運算符才能作為將Obj
分配回自身的保護。
將對象上的級聯樣式表類名稱從A交換為B
查找元素
如果對象的CSS類名稱是nameA,則將其設置為nameB,否則,將其設置為nameA
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);">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.