2011-11-22 3 views
0

커피 스크립트에서 하나의 등호 while 루프 : 여기마 내가 커피 스크립트에 다음 JS를 코딩하기 위해 노력하고있어

x = 0; 
if(node.offsetParent) { 
    do { 
    x += node.offsetLeft; 
    } while(node = node.offsetParent); 
}  

내가 지금까지 가지고 있지만, 노드가 다시 널 올 것으로 보인다 무엇

if node.offsetParent 
    loop 
    x += node.offsetLeft 
    break if typeof (node = node.offsetParent) == "undefined" 
x 
+0

코드가 올바르게 보입니다. – thejh

+0

죄송합니다. 노드 변수가 null로 되돌아 갔어야합니다. – agmcleod

+0

오른쪽. 왜 안돼? – thejh

답변

1

문제는 단순히 DOM 요소 node에 오프셋 부모가없는 경우 node.offsetParentnull이고 undefined이 아니라는 점입니다. typeof null'object'이고 'undefined'이 아닙니다.

왜 원래의 JS 루프와 동일한 접근 방식을 사용하지 않습니까? 단순히 거짓말을 위해 node.offsetParent을 확인 했습니까? 그런 다음 코드는 같이 보일 수 있습니다

x = 0 
if node.offsetParent 
    loop 
    x += node.offsetLeft 
    break unless (node = node.offsetParent) 
x 

나는 또한 당신의 if 불필요한을, 커피 스크립트는 더 do..while 구문이없는 동안, 당신은 단순히이 경우에 while 루프를 사용할 수 있다는 점을 지적하고 싶습니다 :

x = 0 
while node.offsetParent 
    x += node.offsetLeft 
    node = node.offsetParent 
x 
+0

그 트릭을 않습니다, 대단히 감사합니다 :) – agmcleod

관련 문제