Javascript中的return语句?

Javascript中的return语句?,javascript,jquery,Javascript,Jquery,我的JavaScript代码如下: $('[id^="thresholdParameter_"]').each(function(i, value) { //any field is edited if($(this).val() !== previousThresholdParameters[i]){ alert('Hello'); return true; } }); 在这里,我希

我的JavaScript代码如下:

$('[id^="thresholdParameter_"]').each(function(i, value) {  

        //any field is edited
        if($(this).val() !== previousThresholdParameters[i]){
            alert('Hello');
            return true;
        }
    });
在这里,我希望一旦它达到
返回true它必须来自函数并返回真值。然而,它仍在继续着


为什么会这样?JavaScript中的return与Java中的return不同???

每个回调中的return false只会停止每个函数

请参见jQuery中的最后一个示例:

您可以尝试以下方法:

var conditionMet = false;

$(selector).each(function() {
  if (innerConditionMet) {
    conditionMet = true;
    return false; // stop the each
  }
});

使用
return false
而不是
return true
,因为
return true
被视为
continue
return false
被视为
$中的
中断
。每个循环

$('[id^="thresholdParameter_"]').each(function(i, value) {  
    //any field is edited
    if($(this).val() !== previousThresholdParameters[i]){
        alert('Hello');
        return false; // use false
    }
});

我们可以通过使 回调函数返回false。返回非false与 for循环中的continue语句;它将立即跳到下一个 迭代


尝试此操作,因为在您的情况下,它看起来像是要返回
true
,并在其他地方使用:

var flag = false;
$('[id^="thresholdParameter_"]').each(function(i, value) {  
  //any field is edited
  if($(this).val() !== previousThresholdParameters[i]){
    alert('Hello');
    flag = true;
    return false;
  }
});

retun false以突破$each()

试一下这把小提琴,以便更好地理解:


1.
2.
3.
4.
5.
6.
7.
$('.number h1')。每个(函数(){
var h1Value=$(this.text();
如果(H1值==5){
返回false;
}否则{
$(this.css(“背景色”,“#f1ef”);
}
});

它将为所有h1添加背景色,直到达到数字5,然后从$中中断。每个循环

请确保满足条件并执行警报语句。下次请阅读…我认为您应该使用“返回假”;而不是“返回真”;来中断循环
var x = $('[id^="thresholdParameter_"]');

for(i in x){

if(x[i] !== previousThresholdParameters[i]){

 alert('Hello');
 return true; //
 break;

 }
}
var x = $('[id^="thresholdParameter_"]');

for(i in x){

if(x[i] !== previousThresholdParameters[i]){

 alert('Hello');
 return true; //
 break;

 }
}