问题
I have some code like so:
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)
}
}
However it doesn't work and I retrieve the following error TypeError: theQuantities[i].val is not a function
I think I need to use .each however I need to reference theValues
and theDisounts
as well.
What is the correct way to access other selectors with the same index within the .each() function?
Something like this that can also access the theValues
and theDisounts
as well:
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);
}
});
回答1:
When calling a jquery array object using brackets (like theQuantities[i]
) you're getting back an HTML node element, not a jQuery object.
try using theQuantities.eq(i)
which will return the jQuery object in position i, then you can use jQuery's val()
for more on eq, see jQuery documentation: https://api.jquery.com/eq/
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
回答2:
You can try this
var theSubTotal = parseFloat(($(theQuantities[i]).val() * $(theValues[i]).val()) - $(theDiscounts[i]).val()).toFixed(2);
来源:https://stackoverflow.com/questions/39740918/jquery-each-function-accessing-other-selector-via-indexes