How to escape from for … each loop and method at t

2019-08-16 01:23发布

问题:

I am using the code below, that iterating over select options. I checked if options value has already entered. It escapes from for-each but it doesn't exit from method.

yeniIlacBagla_ilacBagla: function(){
    $("#bagliIlaclar > option").each(function(){
        if(this.value===$("#baglanacakIlacID").val()){
            alert($("#baglanacakIlacAdi").val()+'\n adlı ilaç zaten bağlıdır!'); 
            return;
        }else{
            $("#bagliIlaclar").append($('<option></option>').val($("#baglanacakIlacID").val()).html($("#baglanacakIlacAdi").val()));
        }
    });
}

回答1:

According to the documentation of jquery I found the following

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.



回答2:

From the documentation at http://api.jquery.com/each/ :

You can stop the loop from within the callback function by returning false.