[英]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.