【发布时间】: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