問題
這是因爲由。每個執行的功能只從該函數的範圍返回。它不從selected_sheet返回。
事實上,如果你明確地使傳遞到每個顯式的函數返回一個值,你會發現,z爲實際從未設置:
function selected_sheet() {
$('.sheet_radio').each(function() {
return 5;
});
// nothing is actually being returned
};
z = selected_sheet(); // z is undefined
解決方案
一種解決方案是設置默認x值在外部示波器(或保留它未定義),然後將x的值設置爲新值(如果單選按鈕被選中)
function selected_sheet() {
var x = 7; // set default to 7
$('.sheet_radio').each(function() {
if (this.checked == true) {
x = 5; // set to new value
console.log(x);
return false; // stop iterating
}
});
return x;
};
另一種方法是查詢與選擇,看看是否有被檢查單選按鈕:
function selected_sheet() {
if($('.sheet_radio:checked').length > 0) {
return 5;
} else {
return 7; // this is the default if nothing is checked
}
}
最後這裏是一個純JavaScript解決方案:
function selected_sheet() {
if(document.querySelector('.sheet_radio:checked') !== null) {
return 5;
} else {
return 7; // this is the default if nothing is checked
}
}
和簡潔版本
function selected_sheet() {
return document.querySelector('.sheet_radio:checked') !== null? 5 : 7;
}
記得在發帖時提問。 –
那麼''each'裏的'console.log'成功返回'5'? – Shawn31313