2012-12-22 2 views
0

두 번째 스크립트가 실행되는 이유는 무엇이며 어떻게 토글 컨트롤처럼 작동하게 할 수 있습니까?예기치 않은 스크립트 실행 순서

<script> 
    var el = 2; 

    $(document).ready(function(){ 
     $(".rightDiv").click(function(){ 
      if (el == 2) { 
       $(this).animate({left:'150px'}); 
       el = 1; 
      } 
     }); 
    }); 
</script> 

<script> 

    $(document).ready(function(){ 
     $(".rightDiv").click(function(){ 
      if (el==1) { 
       $(this).animate({left:'50px'}); 
       el = 2; 
      } 
     }); 
    }); 
</script> 
+2

2 개의'click' 콜백을 첨부했기 때문에 두 명령문을 모두 실행합니다. 새 이벤트 핸들러를 연결하기 전에 현재 이벤트 핸들러를 제거하는 방법은 http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery를 확인하십시오. – h2ooooooo

답변

0

이 당신을 위해 잘 작동합니다 : 당신은 두 개의 이벤트 핸들러를 atteached 한

var el = false; 
$(document).ready(function() { 
    $(".rightDiv").click(function() { 
     $(this).stop(true).animate({left: (el ? 50 : 150) + 'px'}); 
     el = !el; 
    }); 
});​ 

jsfiddle with example

0

, 이벤트가 그 다음 다른 하나를 실행 어떻게 그렇게 할 때.

첫 번째 변수가 변수를 변경하여 두 번째 조건이 참이되면 if 문 안의 코드가 실행됩니다. 당신은 필요

<script> 
    $(document).ready(function(){ 

    var el = 2; 

    $(".rightDiv").click(function(){ 
     if (el == 2) { 
     $(this).animate({left:'150px'}); 
     el = 1; 
     } else { 
     $(this).animate({left:'50px'}); 
     el = 2; 
     } 
    }); 

    }); 
</script> 
1

)

$(document).ready(function() 
{ 
    var el = false; 
    var rightDivs = $('.rightDiv'); 
    $(rightDivs).click(function(){ 
     if (el == false) 
     { 
     $(this).animate({left:'150px'}); 
     el = true; 
     } 
     else if (el == true) 
     { 
     $(this).animate({left:'50px'}); 
     el = false; 
     } 
    }); 
}); 
0

here's 하나 .ready를 (: 당신이 그 중 하나를 실행하는 else을 사용할 수 있도록

, 동일한 이벤트 핸들러에 코드를 넣어 @ h2ooooooo의 대답을 약간 개선 한 버전으로 전역 범위 변수를 파기하고 요소의 속성을 사용했습니다.

기본적으로 여기서는 전역 변수를 사용하여 전역 범위를 확장하는 것을 방지하기 위해 누른 요소에 직접 관련된 데이터로 작업하고 있습니다.

$(document).ready(function() { 
    $(".rightDiv").attr("isLeft",1).click(function() { 
     var pos = "50"; 
     if($(this).attr("isLeft") == "1"){ 
      pos = "150"; 
      $(this).attr("isLeft",0) 
     }else{ 
      $(this).attr("isLeft",1); 
     } 
     $(this).stop(true).animate({left: pos + 'px'}); 
    }); 
}); 
+0

'.attr()'대신에'.data()'를 사용해야한다. (게다가'- data '를 붙이지 않고서는 사용자 정의 속성을 설정해서는 안된다.) – h2ooooooo

관련 문제