As the title reads, I'd like to pass show() & hide() jQuery functions as parameters in another function.

function applyActionOnClass(attr, action) {
    $('#salesonhold_table tr').each(function () {
    if ($(this).attr('status') == attr)
        $(this).action;
    });
}

Here is when I call my applyActionOnClass function:

$(document).on('change', '.checkboxes', function () {
    var attr = $(this).val();
    if ($(this).is(':checked'))
        applyActionOnClass(attr, show());
    else
        applyActionOnClass(attr, hide());
});

To explain a bit the purpose of this, I have a table and each of its <tr> has a status attribute which differs them from each other. I have two checkboxes on top of the table, one for each possible status value and I'd like to hide/show corresponding <tr> when checkboxes are triggered.

The trigger and stuff work fine but when it comes to $(this).action; it says hide is not defined. Any idea what I did wrong there?

Thank you so much !

有帮助吗?

解决方案

You can pass an anonymous function (or delegate) instead. This code handles that:

function applyActionOnClass(attr, func) {
    $('#salesonhold_table tr').each(function () {
    if ($(this).attr('status') == attr)
        func($(this));
    });
}

This code passes the delegate in:

$(document).on('change', '.checkboxes', function () {
    var attr = $(this).val();
    if ($(this).is(':checked'))
        applyActionOnClass(attr, function(e) { e.show(); });
    else
        applyActionOnClass(attr, function(e) { e.hide(); });
});

其他提示

Another solution is to change your function like so

function applyActionOnClass(attr, action) {
    $('#salesonhold_table tr').each(function () {
    if ($(this).attr('status') == attr)
        $(this)[action]();
    });
}

Note $(this)[action](); You can see it at work here http://jsfiddle.net/t6rEE/ as a proof of concept (and I tried both with hide and show)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top