Можно ли вернуться через несколько функций?
У меня есть функция jQuery on click с циклом $.each. В цикле $.each я тестирую различные условия, а если не встречаю, выводит предупреждающее сообщение, а затем возвращается. Вот вырезанная версия моего кода:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
Однако возврат будет только разорвать этот цикл цикла $.each и запустить следующий цикл. Я хотел бы не только разорвать цикл $.each, но полностью вернуться из функции щелчка.
Чтобы выйти из $.each
вы должны return false
Чтобы выйти из функции обработчика событий, вы должны использовать return
В соответствии с вашим требованием вы можете сделать немного, как показано ниже,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Проверьте документы для jQuery.each()
:
Мы можем разбить цикл $.each() на конкретной итерации, заставив функцию обратного вызова вернуть false. Возврат не-false - это то же самое, что и оператор continue в цикле for; он немедленно перейдет к следующей итерации.
По сути, используйте return false;
вместо того, чтобы просто return;
,
return false;
перед вашей последней скобкой. Примечание . Это остановит действие события по умолчанию и распространение события.