我試圖從檢索變量,如果嵌套在一個jQuery .each
函數聲明:如果從嵌套。每個函數語句檢索變量
var radioAmount;
$('div.amount').each(function() {
var input = $(this).find('input[type="radio"]');
if(input.is(':checked')) {
radioAmount = input.attr('value');
} else {
radioAmount = $('#other-amount').val();
}
});
console.log(radioAmount);
我想radioAmount
到.each
外返回的輸入值函數,但它返回undefined。
我敢肯定這應該是相當簡單的,具有可變範圍做,但我不能工作了,我做錯了什麼。
或者,也許這是錯誤的做法完全。
[顯示您的代碼是工作(http://jsfiddle.net/EDBZ8/)。你的收音機有價值嗎? '#other-amount'是否存在?它是某種形式的元素嗎?它有價值嗎? –
如果'radioAmount'是'undefined',那麼你還沒有向我們展示其他東西。可能性是'radioAmount'沒有被定義在足夠高的範圍內(在'.each()'回調之外),或者你正在做一些異步函數並期待'radioAmount'從中返回。此外,爲什麼使用'.each()'循環,如果你只需要一個'radioAmount'的值 - 這對我來說沒有意義,因爲它只能有一個值,但是你正在遍歷潛在的許多項目並重置價值一遍又一遍。如果你只想要一個值,然後選擇其中一個div – jfriend00
其他可能性。 'input'沒有'value'屬性,或者$('#other-amount')'不存在或沒有值。 – jfriend00