javascript - jquery中如何调用$(function)

标签 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);

                },

            });
        });
    }

});

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

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

    })

我收到错误性能不是函数。我尝试过 $.performance()jQuery.performance() 并且我还尝试将其分配给一个变量,例如:

perf = $(function(){
    performance();
    function performance(){
       pHandler = setTimeout(performance,3000)
     .......

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

This question is differ than JavaScript error: "is not a function" for the following:

It is meant by Jquery so someone may, mistakenly, regard that multiple document.ready(function()) as one scope for Jquery

最佳答案

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

$(function () { // the anonymous function
    function performance() {
        // your function
    }
});

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

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

// execute it when the document loads
$(performance);

这将在更高的范围内定义您的函数。这在全局范围内都是可能的。如果这不是您想要的,那么您可以将需要性能的整个上下文包装在一个更大的函数中,并自调用该函数。

关于javascript - jquery中如何调用$(function),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118608/

相关文章:

jquery - 可搜索/可过滤的 TreeView

javascript - 优化 jQuery 以避免 Safari : “This webpage is using significant energy...”

Javascript - 跟随链接,复制 URL 并更改原件?

javascript - Angular .js :12759 : OPTIONS 405 (Method Not Allowed)

javascript - 动态导航链接

javascript - 如何通过单击文本框jquery使表格可见

javascript - 有没有办法在网页中声明所有 javascript http 请求必须仅针对同一主机?

javascript - 在 javascript 函数中使用 jquery animate

javascript - JQuery 设置 json 值 : path provided as string

javascript - 延迟循环元素