что не так с этой функцией jQuery? - PullRequest
0 голосов
/ 29 июля 2011

У меня был этот код обработчика событий 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, для которой я пытался сделать это способом, который вообще не работает,

(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?

спасибо ..

Ответы [ 3 ]

2 голосов
/ 29 июля 2011

Моя ставка:

// 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');

Также позволяет привязывать несколько селекторов, использовать цепочку и т. Д. Я также явно вызываю join в массиве userId вместо того, чтобы разрешить javascript по умолчанию преобразовывать массив в строку. Это кажется более читабельным для любого, кто просматривает код, ИМХО.

1 голос
/ 29 июля 2011
$('#activate-user').userOperation("block");

Параметру data требуется строка, а ваш аргумент задает параметр data, поэтому передайте ему действие, которое вы хотите выполнить, т.е. строку.

1 голос
/ 29 июля 2011

Например, вы передаете функцию userOperation, но она ожидает строку.

Вместо этого:

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

Сделайте это:

$('#activate-user').userOperation('block');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...