2016-09-28 43 views
0

我有一些代碼,就像這樣:jQuery的。每()函數通過索引訪問其他選擇

var theQuantities = $('#' + theWindowID + '_form INPUT[name=f\\[invoices_items\\]\\[quantity\\]\\[\\]]'); 
var theValues = $('#' + theWindowID + '_form INPUT[name=f\\[invoices_items\\]\\[value\\]\\[\\]]'); 
var theDiscounts = $('#' + theWindowID + '_form INPUT[name=f\\[invoices_items\\]\\[discount\\]\\[\\]]'); 
var theInvoiceTotalCell = $('#' + theWindowID + '_TDinvoice_total'); 
var invoiceTotal = 0; 
for (var i = 0; i < theQuantities.length; i++) { 
    if ($.isNumeric(theQuantities[i].val()) && $.isNumeric(theValues[i].val()) && $.isNumeric(theDiscounts[i].val())) { 
     $('#' + theWindowID + '_' + theRowIDs[i].val() + '_TDinvoice_items_subtotal').html('$ ' + parseFloat((theQuantities[i].val() * theValues[i].val()) - theDiscounts[i].val()).toFixed(2)); 
     var theSubTotal = parseFloat((theQuantities[i].val() * theValues[i].val()) - theDiscounts[i].val()).toFixed(2); 
     invoiceTotal += parseFloat(theSubTotal) 
    } 
} 

但是它不工作,我檢索以下錯誤TypeError: theQuantities[i].val is not a function

我想我需要使用.each,但我需要參考theValuestheDisounts以及。

在.each()函數中訪問其他具有相同索引的選擇器的正確方法是什麼?

像這樣的東西也可以訪問theValuestheDisounts還有:

theQuantities.each(function(index, item) { 
    if ($.isNumeric(this.val()) && $.isNumeric(theValues[index].val()) && $.isNumeric(theDiscounts[index].val())) { 
     $('#'+theWindowID+'_'+theRowIDs[index].val()+'_TDinvoice_items_subtotal').html('$ ' + parseFloat((this.val() * theValues[i].val()) - theDiscounts[i].val()).toFixed(2)); 
     var theSubTotal = parseFloat((this.val() * theValues[i].val()) - theDiscounts[i].val()).toFixed(2); 
     invoiceTotal += parseFloat(theSubTotal); 
    } 
    }); 
+0

你明白了什麼,當您登錄'theQuantities'? – LinkinTED

+0

'theValues [index]'與''.get()'](https://api.jquery.com/get/)在'theValues''上調用相同 - >它返回DOM節點。改用['.eq()'](https://api.jquery.com/eq/) – Andreas

回答

3

當調用使用括號你要回一個HTML節點元素,而不是一個jQuery一個jQuery數組對象(如theQuantities[i])目的。 嘗試使用theQuantities.eq(i)將返回jQuery對象的位置我,那麼你可以使用jQuery的val()

更多關於EQ,看到jQuery的文檔:https://api.jquery.com/eq/

如果提供的jQuery代表了一組DOM的元素,.eq()方法從該集合中的一個元素構造一個新的jQuery對象。提供的索引標識該元素在集合中的位置。

0

你可以試試這個

var theSubTotal = parseFloat(($(theQuantities[i]).val() * $(theValues[i]).val()) - $(theDiscounts[i]).val()).toFixed(2);