2014-09-16 2 views
1

클릭 할 버튼을 청취하고 클릭 한 버튼에 따라 해당 객체 속성을 전환하는 메소드를 작성하려고합니다. 1과 0입니다. 나는 길을 벗어난 길일 수도 있지만, 한 가지 방법과 "this"키워드로 이것을 수행 할 수 있습니까? 내 코드는 내 진보이지만 나는 갇혀있다. http://jsfiddle.net/eh8L5cg1/javascript 객체, 다른 속성의 값을 전환하고 DRY 코드를 작성하는 방법

<input type="button" id="buttonOne" value="toggle buttonOne" /> 
<input type="button" id="buttonTwo" value="toggle buttonTwo" /> 
<input type="button" id="buttonThree" value="toggle buttonThree" /> 

var controlPannel = { 
    buttonOne : 0, 
    buttonTwo : 0, 
    buttonThree : 0 
    toggleState: function() { 

     $('button').click(function() { 

      if (controlpannel.this == 0) { 
       controlpannel.this = 1; 
      } else { 
       controlpannel.this = 0; 
      } 
     }); 

    } 

} 

답변

2

당신이 할 수있는 예) 코드 내 주석을 참조하십시오. 그리고 여기에 업데이트 된 바이올린 링크가 있습니다 : http://jsfiddle.net/bmartinelle/eh8L5cg1/1/

var controlPannel = { 
    buttonOne : 0, 
    buttonTwo : 0, 
    buttonThree : 0, 
    toggleState: function() { 
     $(':button').click(function() { 
      //"this" is the button - you need to fetch the id to access the property or your controlPannel 
      console.log(controlPannel[this.id]); 
      if (controlPannel[this.id] == 0) { //JS is case-sensitive - so make sure you use proper camelCasing 
       console.log("toggle to 1"); 
       controlPannel[this.id] = 1; 
      } else { 
       controlPannel[this.id] = 0; 
       console.log("toggle to 0"); 
      } 
     }); 
    } 

} 
controlPannel.toggleState(); //be sure to actually assign the click handlers to your buttons! 
+1

Awsome! 이 부분은 ': 버튼'을 의미합니까? the : 나에게 처음이다. – user3749553

+2

페이지의 모든 '버튼'을 선택하는 방법입니다. –

관련 문제