2011-02-25 29 views
2
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的新手。所以无法很好地理解上述两个功能。希望有人能够逐一向我解释这条线的含义。非常感谢。javascript中的函数的含义是什么?

回答

4

对于第一功能

var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj; 

第一行获取由它的ID的对象如果Obj是一个字符串,它是一个DOM元素的ID。否则,它将仅保留Obj的值。这是使用“三元条件”运算符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"); 
} 

第二功能刚刚施加第一交换的CSS类的DOM元素的以“MenuBox”和“MenuBox2”之间"Menu_"+iNo ID。


个人,因为它的DOM的两个搜索时,它只是需要做一个我不喜欢的第一个函数的第一行。我会这样做

var Obj = document.getElementById(Obj) || Obj; 

这应该是更有效的所有实现,并且肯定更具可读性。如果仅当document.getElementById返回null,它使用||运营商作为后卫将Obj指定回自己。

0

交易所从一个物体上的级联样式表类名到B

查找元素

如果对象的CSS类名是NAMEA,将其设置为nameB,否则,将其设置为NAMEA

点击 当
0
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);"> 
+0

//运行showMenu功能 为什么不使用它像这样的“ enjoylife 2011-02-25 02:42:54

+1

所以浏览器不会按照链接重新加载t他整页 http://stackoverflow.com/questions/4131834/why-href-is-high-priority-than-onclick – 2011-02-25 02:59:18

相关问题