jQuery .each() function accessing other selector via indexes

混江龙づ霸主 提交于 2020-01-17 05:53:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!