2010-07-02 8 views
1

다음 코드는 페이지의 각 texbox에 대해 두 개의 버튼 (오른쪽의 왼쪽에 하나)을 생성합니다. 아이디어는 증가/감소 텍스트 상자를 만드는 것입니다. 코드는 하나의 텍스트 상자에서 작동하지만 2 개 이상의 모든 단추로 모든 텍스트 상자를 증가/감소시킵니다.JQuery에서 텍스트 상자 용 버튼 만들기 및 클릭 기능 할당하기

비행 중에 버튼을 만들고 증가/감소를 위해 텍스트 상자에 첨부하는 방법을 알려주세요.

jQuery.fn.incrementer = function() { 
    this.val(0); 
    this.before("<input class='incrementer_minus' type='button' value=' - '/>");   
    var myobj = this; 
    $(".incrementer_minus").live('click', function(){ 
     $(myobj).val(parseInt(JQ(myobj).val()) - 1); 
    }); 
    this.after("<input class='incrementer_plus' type='button' value=' + '/>"); 
    $(".incrementer_plus").live('click', function(){ 
     $(myobj).val(parseInt(JQ(myobj).val()) + 1); 
    }); 
} 

JQ("#increment").incrementer(); 
JQ("#increment2").incrementer(); 
+0

'jQuery','JQ' * 및 *'$'를 사용하여'jQuery' 객체를 표현하고 싶습니다.이 모든 이유는 무엇입니까? 같은 줄을 바꾸어도됩니까? 그것은 코드를 훨씬 덜 읽을 수있게 만든다. 당신이 이것을하는 이유가 있다면 궁금하다. –

+0

:) 실제로 나는 JQ 만 사용하지만 다른 코드에서 모든 복사/붙여 넣기를하고있다. 나는 완전히 정리를 잊었다. – Ergec

답변

1

당신은 와 클릭 이벤트를 incrementer_minus의 모든 인스턴스를 연관되어 있습니다 .. 플러그인의 일부이며, incrementer_plus 할 때 :

$(".incrementer_plus").live('click'... 

방금 ​​생성 한 특정 이벤트에 이벤트를 첨부하면됩니다.

live이 필요하지 않으므로 live 대신 bind을 사용했습니다.

또한 편의상 JQjQuery으로 변경했습니다. 다시 변경할 수 있습니다.

테스트를 아웃 : 희망이 (? 여전히) 될 수 http://sean-o.com/increment

난 그냥 그런 사용할 수 있도록 만든 :http://jsfiddle.net/mAsr9/

jQuery.fn.incrementer = function() { 
    var myobj = this; 
    this.val(0); 

     // Create new element, and insert before 'this' 
    jQuery("<input class='incrementer_minus' type='button' value=' - '/>").insertBefore(this) 

      // Then bind the click event to that new element 
     .bind('click', function(){ 
      $(myobj).val(parseInt(jQuery(myobj).val()) - 1); 
     }); 

     // Create new element, and insert after 'this' 
    jQuery("<input class='incrementer_plus' type='button' value=' + '/>").insertAfter(this) 

      // Then bind the click event to that new element 
     .bind('click', function(){ 
      $(myobj).val(parseInt(jQuery(myobj).val()) + 1); 
     }); 
} 

$(function() { 
    jQuery("#increment").incrementer(); 
    jQuery("#increment2").incrementer(); 
}); 
+0

.before() 및 .insertBefore(). 이제 알았어. 나는 더 공부할 필요가있다. – Ergec

+1

@Ergec - 예, 영리한 jQuery 사람들은 우리에게 똑같은 두 가지 방법을 제공했다. 단지 삽입 된 요소와 대상의 순서를 바꾸어서 적절한 연결을 수행 할 수있게 해준다. . 대안은 먼저 새 요소를 만들어 변수에 저장하는 것입니다. 'var $ minusInput = $ ('');'다음은'this.before ($ minusInput);과'$ minusInput.bind (func ...);' – user113716

+0

고맙습니다. – Ergec

0

가 jQuery를 증가 플러그인에서보세요 너에게 도움이된다.