如何在jquery中调用$(function)

Sai*_*akR 0 javascript jquery

我有以下功能:

$(function(){
    performance();
    function performance(){
       pHandler = setTimeout(performance,3000)
        perOb = [];
        alert('hhhh')
        $(".performance").each(function(i){            
            perOb[i] = $(this);
            url = '/cavity/performance/'+perOb[i].attr('data-id')+'/'+jobId;
            //perOb[i].html('%');
            $.ajax({
                type: "GET",
                //dataType: "json",
                url: url,
                success: function(data){
                    perOb[i].html(data.performance+"%");
                },
                error: function(xhr, status, response){
                    console.log(xhr.responseText);

                },

            });
        });
    }

});
Run Code Online (Sandbox Code Playgroud)

我试图从另一个事件中调用它,如下所示:

$('#in-between').change(function(){
        if ($(this).prop('checked')){
            window.clearTimeout(pHandler);
            alert('yesr')            
        }
        else{
            alert('noo')
            performance();
        }

    })
Run Code Online (Sandbox Code Playgroud)

我有错误performance is not a function.我试过了$.performance(),jQuery.performance()我也尝试将它分配给变量,如:

perf = $(function(){
    performance();
    function performance(){
       pHandler = setTimeout(performance,3000)
     .......
Run Code Online (Sandbox Code Playgroud)

并将其称为perf.performance() 但所有尝试的人都没有成功地从事件中调用它.

此问题与JavaScript错误不同 :"不是函数" ,表示以下内容:

它是由Jquery所指,所以有人可能会错误地将多个document.ready(function())视为Jquery的一个范围

Dav*_*vid 5

您只在其父函数的范围内定义了该函数,该函数是在页面加载时执行的匿名函数:

$(function () { // the anonymous function
    function performance() {
        // your function
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您希望它存在于该范围之外,则必须在该范围之外定义它.例如:

// define the function
function performance() {
    // your function
}

// execute it when the document loads
$(performance);
Run Code Online (Sandbox Code Playgroud)

这将在更高的范围内定义您的功能.这可能在全球范围内.如果不希望这样,那么你将performance在一个更大的函数中包含所需的整个上下文并自我调用那个.