javascript jQuery 函数返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20731593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery function returning undefined
提问by Fabricio
My function here is ever returnig undefined, what is wrong?
我这里的函数总是返回未定义,有什么问题吗?
function getTaxType() {
$('.type').each(function() {
if ($(this).data('tax') === 'form1' && $(this).is(':checked')) {
return 'form1';
}
else if ($(this).data('tax') === 'form2' && $(this).is(':checked')) {
return 'form2';
}
else if ($(this).data('tax') === 'form3' && $(this).is(':checked')) {
return 'form3';
}
});
}
回答by Saravana
That's because you're returning from the callback function of $.each
and not from getTaxType
.
那是因为您是从 的回调函数$.each
而不是从 返回getTaxType
。
Try this:
试试这个:
function getTaxType() {
var result;
$('.type').each(function() {
if ($(this).data('tax') === 'form1' && $(this).is(':checked')) {
result = 'form1';
}
else if ($(this).data('tax') === 'form2' && $(this).is(':checked')) {
result = 'form2';
}
else if ($(this).data('tax') === 'form3' && $(this).is(':checked')) {
result = 'form3';
}
});
return result;
}
回答by Deryck
If it's checkboxes there can be more than one which means you have multiple results - storing this in array for you.
如果是复选框,则可以有多个,这意味着您有多个结果 - 将其存储在数组中。
Multiple-Choice:
多项选择:
function getTaxType() {
var result = [];
$('.type:checked').each(function(i) {
var tax = $(this).data('tax');
result[i] = (tax === 'form1' || tax === 'form2' || tax === 'form3') ? tax : false;
});
return result;
};
If you meant to only have one result (radio button), then you remove the = []
on result and the [i]
in the loop.
如果您打算只有一个结果(单选按钮),那么您可以删除= []
on 结果和[i]
in 循环。
Single Answer
单一答案
function getTaxType() {
var tax = $('.type:checked').data('tax');
var result = (tax === 'form1' || tax === 'form2' || tax === 'form3') ? tax : false;
return result;
};
Of course, if it is single answer (aka radio buttons) then you can ONLY have those three form answers which makes it even simpler:
当然,如果它是单一答案(又名单选按钮),那么您只能拥有这三种形式的答案,这使它变得更加简单:
function getTaxType() {
return $('.type:checked').data('tax');
};