JQuery将函数名称传递给变量并调用它

时间:2015-03-01 09:28:02

标签: javascript jquery

我正在调整我的分页,但因为分页只是做GET请求,我打算让它做AJAX Post请求,这样做是因为在一个页面中可以有几个分页。

    $(document).ready(function()
    {
        $(document).on('click', '.pagination a', function(e)
        {
            e.preventDefault();

            var page = $(this).attr('href').split('page')[1];
            var function_name = $(this).parent().closest('div').attr('data-function-name');
    });

我打算使用function_name调用现有函数,然后将该页面作为参数传递给该函数的值

让我们说

function fetch_records(page)
{
    //do something here
}


function fetch_notes(page)
{
    //do something here
}

任何人都可以告诉我如何在不使用EVAL的情况下完成这项工作?感谢。

更新

            <div id="div_paginate" class="col-sm-6" style="display:block;" data-function-name="fetch_records">
                <div id="div_possible_duplicate_paginate" class="pull-right"></div>
            </div>

我想要做的是,对于每个分页div,我将拥有该数据属性,它将包含它应该调用的函数名。

1 个答案:

答案 0 :(得分:2)

您可以创建一个包含所有AJAX方法的模块,并根据您的data-function-name从此容器中调用特定方法。像这样:

测试HTML:

<div id="div_paginate" data-function-name="fetch_records" class="grid">
    Records..
</div>

<div id="div_paginate" data-function-name="fetch_notes" class="grid">
    Notes..
</div>

JS:

// Module that contains your particular methods
var FuncsModule = (function(){
    var fetch_records = function(page)
    {
        alert('fetching records ' + page + '..');
    }
    var fetch_notes = function(page)
    {
        alert('fetching notes ' + page + '..');
    }
    return {
        fetch_records: fetch_records,
        fetch_notes: fetch_notes
    }
})();

// Implementation
$(document).ready(function() {
    $(document).on('click', '.grid', function(e){                                 
        var action = ($(this).attr('data-function-name')),
            page = Math.floor((Math.random() * 10) + 1); // some random number for tests
        if (typeof(action) !== 'undefined'){
            FuncsModule[action].call(this, page);
        }
    });
});

的jsfiddle:

http://jsfiddle.net/avup23cg/

相关问题