【问题标题】:How to call $(function) in jquery如何在 jquery 中调用 $(function)
【发布时间】:2017-05-22 17:14:45
【问题描述】:

我有以下功能:

$(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 is not a function。我试过$.performance()jQuery.performance(),也试过把它赋值给一个变量,比如:

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

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

这个问题不同于 JavaScript error: "is not a function" 对于以下内容:

它是 Jquery 的意思,所以有人可能会错误地认为 多个 document.ready(function()) 作为 Jquery 的一个范围

【问题讨论】:

  • 在两个事件处理程序共享的范围内定义performance(在您的情况下可能是全局范围)。换句话说:将function performance() {} 移到$(function() {}) 之外。看看:What is the scope of variables in JavaScript?
  • 您需要阅读关于 JavaScript 范围的良好入门。 performance 仅在您定义它的函数内部定义。
  • @MikeMcCaughan 请查看更新到问题的报价。
  • 有人可能对两个函数不相同的事实感到困惑这一事实并没有使问题不再重复。

标签: javascript jquery


【解决方案1】:

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

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

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

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

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

这将在更高的范围内定义您的功能。这很可能在全球范围内。如果不希望这样做,那么您可以将需要 performance 的整个上下文包装在一个更大的函数中并自行调用该函数。

【讨论】:

  • 我遵循了您的解决方案,当我在包含 function performance(){... 定义的同一 document.ready() 中定义 $('#in-between') 事件时,它成功了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 2012-10-17
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2017-02-08
相关资源
最近更新 更多