今天我在玩速记语法..发现了两种新的很酷的方法来编写冗长乏味的if语法,还学到了关于闭包的新东西......
这是我想出来的。
这是一个带有一个 eventHandler 的手风琴菜单的切换功能。
function h(e){
var p='parentNode',a=e.target,b=a[p],f=48,u='px',y=b[p];
!y.c||(y.c==b||(y.c.style.height=f+u,y.c.x=f)),
y.c=y.c==b?null:b,
a!=b.firstChild||(b.x=b.x>f?f:
(f+b.childNodes[1].offsetHeight),b.style.height=b.x+u)
}
Run Code Online (Sandbox Code Playgroud)
这是示例。
http://jsfiddle.net/YjCbM/(使用 Chrome 29 测试)
有一个错误..这是工作http://jsfiddle.net/YjCbM/1/
在这个例子中,我使用 e.target、webkit css3 和其他各种 ie 和其他浏览器不支持的东西,但除此之外……这个速记语法在旧版/其他浏览器上是否有效?
ps.: 不要在 jsfiddle 中整理代码,否则无效
在我得到一些答案后编辑..
一些有用的速记
var W=window,D=W.document,G='getElementById',
E=W.addEventListener?'addEventListener':'attachEvent',
// this awesome as i don't use jQuery.
// this way i have a short getElementbyId() like jQuery's $()
// and also a ie compatible addEventListener.
a=D[G](x);
//document.getElementById(x)
a[E]('click',handler);
//a.addEventListener() or a.attachEvent()
a=x?y:x
//if x is defined, true, or not 0 it will take the y value
if ( x == true ) {
a = y;
}else{
a = x;
}
a=x||y;
//if x is not defined it will take y
if ( x == true ) {
a = x
}else{
a = y
}
x||(x=y,alert(x)) // <- this is fabulous
// if x is not defined, not true, or 0 it will set the x with the y value
// and alert x
if ( x == 'undefined' ) {
x = y;
alert ( x );
}
// how manytimes did it happen that you wanted to do just a short check but you hat to
//set 2-3 variables and could not use a simple a=x||y
// whith this shorthand you can.
var a = 1;
var b;
var c = a;
// is the same as
var a=1,b,c=a;
Run Code Online (Sandbox Code Playgroud)
编辑2
我收到了所有这些downvotes的问题禁令。但我真的不明白为什么我得到了这么多的反对...请解释你的反对。
如果您指的是三元运算符 ,?:那么是的,所有浏览器都支持它。
它是这样使用的:
condition ? ifTrue : ifFalse
Run Code Online (Sandbox Code Playgroud)
例如:
'You have ' + (milkAmount <= 0 ? 'no' : (milkAmount + ' cups')) + ' of milk!'
Run Code Online (Sandbox Code Playgroud)
如果您指的是 or 运算符||,那么也可以。例如:
a || b || c
Run Code Online (Sandbox Code Playgroud)
这将找到的第一个变量出来a,b和c选择的第一个不是falsy(undefined,0,false,NaN,等)。
| 归档时间: |
|
| 查看次数: |
1721 次 |
| 最近记录: |