2011-02-04 2 views
1

내 asp.net 프로젝트의 공통 javascript 파일에이 코드가 있습니다.이 jquery 함수를 간결하게 만들려면 어떻게해야합니까?

jQuery-Lint는이 함수의 영향을받은 버튼 위에 마우스를 올릴 때마다 "두 번 이상 같은 선택기를 사용했습니다."를 반환합니다.

//turns all the buttons into jqueryUI buttons 
//#mainBody is on the master page, #childBody is on the modal page. 
$("#mainBody button, #mainBody input:submit, #mainBody input:button, #childBody button, #childBody input:submit, #childBody input:button").livequery(function() { 
    $(this).button().each(function (index) { 
          $(this).ajaxStart(function() { 
            $.data(this, "old_button_val", $(this).val()); 
            $.data(this, "old_button_disabled", $(this).button("option", "disabled")); 
            $(this).button("option", "disabled", true).val("Wait..."); 
           }).ajaxStop(function() { 
            $(this).val($.data(this, "old_button_val")).button("option", "disabled", $.data(this, "old_button_disabled")); 
           }).ajaxError(function() { 
            $(this).val($.data(this, "old_button_val")).button("option", "disabled", $.data(this, "old_button_disabled")); 
           }); 
         }); 
}); 

비슷한 질문이 대답 here.

+1

여기서'.each'를 사용할 필요가 없습니다 – mVChr

답변

2
// Might be a good idea now to add a class to these element 
// instead of using a long selector like this 
// Additionally, :button already includes <button> elements 
var selector = "#mainBody input:submit, #mainBody input:button, #childBody input:submit, #childBody input:button"; 

$(selector).livequery(function() { 
    // Store a copy of $(this), which we'll reuse... and reuse... and reuse 
    var t = $(this); 

    // Create the callback function shared berween 
    // ajaxStop and ajaxError 
    function ajaxCallback() { 
     t.button('option', { 
      label: t.data("old_button_val"), 
      disabled: t.data('old_button_disabled') 
     }); 
    } 

    t.button() 
     .ajaxStart(function() { 
      // Use $.fn.data instead of $.data 
      t.data({ 
       // Using 'label' instead of 'val' 
       // because <button> elements do not have 'value's 
       "old_button_val", t.button('option', 'label'), 
       "old_button_disabled": t.button("option", "disabled") 
      }).button('option', { 
       disabled: true, 
       label: 'Wait...' 
      }); 
     }).ajaxStop(ajaxCallback).ajaxError(ajaxCallback); 
    }); 
}); 

면책 조항 : 테스트하지 않았으므로 작동하지 않을 수도 있습니다.

+0

참고 : .data에 키/값 쌍 객체를 전달하려면 jQuery 1.4.3 이상을 사용해야합니다! 그렇지 않으면이 스크립트에서 "e is undefined"와 같은 오류가 표시 될 수 있습니다. –

관련 문제