Javascript 通过所有函数返回
是否可以通过多个功能返回? 我有一个jQuery on click函数,其中每个循环都有$。在$.each循环中,我测试各种条件,如果不满足,则显示警报消息,然后返回。以下是我的代码的精简版本:Javascript 通过所有函数返回,javascript,jquery,function,Javascript,Jquery,Function,是否可以通过多个功能返回? 我有一个jQuery on click函数,其中每个循环都有$。在$.each循环中,我测试各种条件,如果不满足,则显示警报消息,然后返回。以下是我的代码的精简版本: $(document).on('click', '.add-to-basket, #add-to-basket', function(e) { var data = { id: $(this).data('id'), quantity: 1 };
$(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循环,而且希望完全从on-click函数返回
本质上,使用
返回false代码>而不是仅返回
退出$。每个都应返回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
谢谢你,这至少让我走了一半。这会永久性地将我从$中分离出来,但不会将我从原始的单击函数中分离出来。然后为单击处理程序放置一个单独的返回语句。我真的不能给你任何代码,因为我不知道你到底想要返回什么。如果您只想离开单击处理程序,请放置returnfalse代码>在最后一个括号之前。注意:这将停止默认事件操作和事件传播。