2011-07-29 3 views
0

나는이 jQuery를 이벤트 핸들러 코드를했고 난 함수이 jQuery 함수의 문제점은 무엇입니까?

$("#activate-user").click(function() { 
    var userId = []; 
    $(':checkbox:checked').each(function(i) { 
     userId[i] = $(this).val(); 
    }); 
    if(userId.length == 0) { 
     //If userId is empty 
    } else { 
     $.ajax({ 
      type: 'POST', 
      url: 'process.php', 
      data: 'option=activate&userId='+userId, 
      success: function(msg){ 
       if(msg == 0) { 
        //If cannot process the query. 
       } else { 
        //If query is processed. 
        location.reload(true); 
       } 
      } 
     }); 
    } 
}); 

$("#block-user").click(function() { 
    var userId = []; 
    $(':checkbox:checked').each(function(i) { 
     userId[i] = $(this).val(); 
    }); 
    if(userId.length == 0) { 
     //If userId is empty 
    } else { 
     $.ajax({ 
      type: 'POST', 
      url: 'process.php', 
      data: 'option=block&userId='+userId, 
      success: function(msg){ 
       if(msg == 0) { 
        //If cannot process the query. 
       } else { 
        //If query is processed. 
        location.reload(true); 
       } 
      } 
     }); 
    } 
}); 

이 두 이벤트 핸들러 사이의 유일한 차이는, option=

  1. data: 'option=activate&userId='+userId
  2. data: 'option=block&userId='+userId 즉 값으로 변환하고 싶어

저는 이것을 이것을 jQuery functio로 바꾸길 원합니다. N하는 나는 전혀 작동하지 않습니다 이런 식으로, 일을 시도

(function ($) { 
jQuery.fn.userOperation = function(opString) { 
    this.click(function() { 
     var userId = []; 
     $(':checkbox:checked').each(function(i){ 
      userId[i] = $(this).val(); 
     }); 
     if(userId.length === 0) { 
      //If userId is empty. 
     } else { 
      $.ajax({ 
       type: 'POST', 
       url: 'process.php', 
       data: 'option='+opString+'&userId='+userId, 
       success: function(msg){ 
        if(msg == 0) { 
         //If cannot process the query. 
        } else { 
         //If query is processed. 
         location.reload(true); 
        } 
       } 
      }); 
     } 
    }); 
} 
}(jQuery)); 

의 jQuery 함수 호출 : 내가 올바르게 인수를 전달하고 있지 않다으로

$('#activate-user').userOperation(function() { 
    return 'block'; 
}); 

이 작동하는 것 같다하지 않습니다 함수, 내가 jQuery에서 초보자로서, 내가 어떻게 해야할지 모르겠다. 나는 어디로 잘못 가고 있니? 인수를 jQuery 함수에 전달하는 정확하고 실현 가능한 방법은 무엇입니까?

userOperation에 함수를 전달하는, 하나

답변

2

내 입찰가 :

// use an anonymous function to we can still reference the short version 
// of jQuery ($) even in situations where $.noConflict() was applied. 
(function($){ 

    // extending the $.fn is saying "We want to add a function as part of jQuery" 
    $.fn.extend({ 

     // here's the new function we're adding: 
     // $(selector).userOperation(action); 
     userOperation: function(action){ 

      // return an each iterator so we can bind to multiple selectors 
      // and so we can chain (e.g. $('#foo,#bar).userOperation('delete').show();) 
      return this.each(function(i,e){ 

       // grab the current element and bind to its click event 
       $(e).click(function(){ 

        // go through the checked boxes and find userIds we're working on 
        // map() makes this easy because it will go through each found item, 
        // process it (in this case return only it's value) then return those 
        // results as an object. Then, we call toArray() so all we have is an 
        // array full of those found values. 
        var userId = $(':checkbox:checked').map(function(i,el){ 
         return $(el).val()); 
        }).toArray(); 

        // check if we have userId entries 
        if (userId.length > 0){ 

         // we have entries, fire off the AJAX call 
         $.ajax({ 
          type: 'POST', 
          url: 'resources/library/models/users/process.php', 
          data: 'option='+action+'&userId='+userId.join(','), 
          success: function(msg){ 
           if (msg == 0){ 
            // cannot process 
           }else{ 
            location.reload(true); 
           } 
          } 
         }); 
        }else{ 
         // userId array is empty 
        } 

        // block action, in case we bind click to anchors 
        e.preventDefault(); 
       }); 
      }); 
     } 
    }); 

})(jQuery); 

// this is how we would attach it to various elements: 
$('#block').userOperation('block'); 
$('#activate').userOperation('activate'); 

또한 당신은 내가 명시 적으로 대신 문자열 배열을 주조로 기본 자바 스크립트를 허용하는 userId 배열에 join 전화 등 여러 선택기를 사용 체인에 결합 할 수 있습니다 . 이것은 IMHO라는 코드를 사용하는 사람들에게 더 읽기 쉽도록 나타납니다.

+0

대부분의 코드가 외계인처럼 보입니다. D, 유감 스럽지만 jQuery에서 초보자입니다. 입찰가와 정확히 무슨 일이 일어나는지에 대해 설명하여 도움을 주시면 감사하겠습니다. –

+0

@ibrahim : 저는 그냥 당신을 위해 그것을 주석. ;-) –

+0

그 종류의 당신, 고마워요 :) –

1

.. 감사합니다,하지만 문자열을 기대하고있다. 대신이의

:

$('#activate-user').userOperation('block'); 
+0

좋아요, 어떻게 함수 대신 문자열을 전달합니까? –

+0

확장 된 답변보기 – FishBasketGordo

1
$('#activate-user').userOperation("block"); 

는 데이터 매개 변수는 고통을 필요로하고 인수가 데이터 매개 변수를 만드는, 그래서 당신이 원하는 행동을 통과 :

$('#activate-user').userOperation(function() { 
    return 'block'; 
}); 

는이 작업을 수행 받아 IE 문자열.

관련 문제