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

JQuery pass function name to a variable and calling it

本文关键字:变量 调用 函数 JQuery      更新时间:2024-07-05

我正在调整我的分页,但由于分页只执行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,我都有一个数据属性,它将包含它应该调用的函数名。

您可以制作一个模块,该模块将包含所有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/