繁体   English   中英

使用 Javascript 从动态生成的表中的 HTMLCollection 获取值

[英]Get values from HTMLCollection in a dynamically generated table with Javascript

我在尝试从我的表中获取值时遇到了这个问题(这些 tds 是在按钮单击时生成的)并添加了类名

prdctNameSpace.className = 'subTotal';

这是我的 JS function

 var arr=document.getElementsByClassName('subTotal');
    console.log(arr.length);

var tot=0;
for(var i=0;i<arr.length;i++)
{
    tot += parseFloat(arr[i].value);
}
console.log(tot);

document.getElementById('totalprod').innerHTML = tot;

我的 HTML 中的 output 是 NaN。 第一个 console.log() 运行良好,因为每次我添加新的时它都会添加 +1。 我只是无法得出这些值的总和。

 var addShopList = function() { // Ajouter un element au tableau var product = document.getElementById("shopList").options[document.getElementById('shopList').selectedIndex].text; var quantity = document.getElementById("qte").value; var sum = document.getElementById("shopList").value; var total = parseInt(quantity) * parseFloat(sum); var tbody = document.querySelector('#sellTable tbody'); var trproduct = document.createElement('TR'); tbody.appendChild(trproduct); var tbodytr = tbody.lastChild; //Making 1st Row var prdctNameSpace = document.createElement('TD'); tbodytr.appendChild(prdctNameSpace); //First Row content var prdctName = document.createTextNode(product); prdctNameSpace.appendChild(prdctName); prdctNameSpace.className = 'subTotal'; var productQteSpace = document.createElement("TD"); tbodytr.appendChild(productQteSpace); //2nd col Content var productQte = document.createTextNode(quantity); productQteSpace.appendChild(productQte); //3rd Col var productSinglePriceSpace = document.createElement("TD"); tbodytr.appendChild(productSinglePriceSpace); var productSinglePrice = document.createTextNode(parseInt(sum).toFixed(3) + " DT"); productSinglePriceSpace.appendChild(productSinglePrice); //4th col var productTotalPriceSpace = document.createElement("TD"); tbodytr.appendChild(productTotalPriceSpace); var productTotalPrice = document.createTextNode(parseFloat(total).toFixed(3) + " DT"); productTotalPriceSpace.appendChild(productTotalPrice); var productDeleteSpace = document.createElement("TD"); var productDeletebtn = document.createElement("BUTTON"); //tbodytr.appendChild(productDeleteSpace); productDeletebtn.setAttribute('class', 'btn x'); productDeletebtn.name = 'delrow'; productDeletebtn.textContent = "X"; tbodytr.appendChild(productDeletebtn); console.log(productDeletebtn.name); productDeletebtn.setAttribute('onclick', 'delRowList(this)'); var arr = document.getElementsByClassName('subTotal'); console.log(arr.length); var tot = 0; for (var i = 0; i < arr.length; i++) { tot += parseFloat(arr[i].value); } console.log(tot); document.getElementById('totalprod').innerHTML = tot; } function emptyQte() { if (document.getElementById('qte').value === "") { document.getElementById('ajout').disabled = true; } else { document.getElementById('ajout').disabled = false; } } var delRowList = function(btn2) { var delbtn = document.getElementById('sellTable'); delbtn.deleteRow(btn2.parentNode.rowIndex); } var setupListeners = function() { var btn = document.getElementById('ajout'); btn.addEventListener('click', addShopList); } window.addEventListener('load', setupListeners);
 <select id="shopList" onlick="summ()" class="form-select form-select-lg mb-3"> <option selected disabled="disabled"> Liste Des Produits</option> <optgroup label="Femme"> <option value="40" name="PullVegeta2"> Top Femme Colle V </optgroup> <optgroup label="Homme"> <option value="35" name="PullVegeta3">Pull Homme OpenMinded <option value="30" name="PullVegeta">Pull Homme Vegeta </optgroup> </select> <input type="text" id="qte" placeholder="Quantité" onkeyup="emptyQte()" onkeypress="return (event.charCode == 8 || event.charCode == 0)? null: event.charCode >= 48 && event.charCode <= 57" required/> <input type="button" value="Ajouter" id="ajout" disabled> <table id="sellTable" class="table"> <thead> <tr> <th scope="col">Nom Produit</th> <th scope="col">Quantité</th> <th scope="col">Prix Unitaire</th> <th scope="col">Total Produit</th> <th scope="col">Action</th> </tr> </thead> <tbody> </tbody> <tfooter> <td colspan="3">Somme Total:</td> <td id="totalprod"> DT</td> <td> <button>Paiement</button></td> </tfooter> </table>

现场版: https://jsfiddle.net/ajkpo47L/

prdctNameSpace<td> ,而不是<input> 它没有value属性。

您应该使用.textContent而不是.value来获取内容。

此外,您将subTotal class 放在错误的元素上。 您将其放在带有产品名称的单元格上,而不是该产品的总价格。

 var addShopList = function() { // Ajouter un element au tableau var product = document.getElementById("shopList").options[document.getElementById('shopList').selectedIndex].text; var quantity = document.getElementById("qte").value; var sum = document.getElementById("shopList").value; var total = parseInt(quantity) * parseFloat(sum); var tbody = document.querySelector('#sellTable tbody'); var trproduct = document.createElement('TR'); tbody.appendChild(trproduct); var tbodytr = tbody.lastChild; //Making 1st Row var prdctNameSpace = document.createElement('TD'); tbodytr.appendChild(prdctNameSpace); //First Row content var prdctName = document.createTextNode(product); prdctNameSpace.appendChild(prdctName); var productQteSpace = document.createElement("TD"); tbodytr.appendChild(productQteSpace); //2nd col Content var productQte = document.createTextNode(quantity); productQteSpace.appendChild(productQte); //3rd Col var productSinglePriceSpace = document.createElement("TD"); tbodytr.appendChild(productSinglePriceSpace); var productSinglePrice = document.createTextNode(parseInt(sum).toFixed(3) + " DT"); productSinglePriceSpace.appendChild(productSinglePrice); //4th col var productTotalPriceSpace = document.createElement("TD"); tbodytr.appendChild(productTotalPriceSpace); var productTotalPrice = document.createTextNode(parseFloat(total).toFixed(3) + " DT"); productTotalPriceSpace.className = 'subTotal'; productTotalPriceSpace.appendChild(productTotalPrice); var productDeleteSpace = document.createElement("TD"); var productDeletebtn = document.createElement("BUTTON"); //tbodytr.appendChild(productDeleteSpace); productDeletebtn.setAttribute('class', 'btn x'); productDeletebtn.name = 'delrow'; productDeletebtn.textContent = "X"; tbodytr.appendChild(productDeletebtn); console.log(productDeletebtn.name); productDeletebtn.setAttribute('onclick', 'delRowList(this)'); var arr = document.getElementsByClassName('subTotal'); console.log(arr.length); var tot = 0; for (var i = 0; i < arr.length; i++) { console.log(arr[i].textContent); tot += parseFloat(arr[i].textContent); } console.log(tot); document.getElementById('totalprod').innerHTML = tot.toFixed(3) + ' DT'; } function emptyQte() { if (document.getElementById('qte').value === "") { document.getElementById('ajout').disabled = true; } else { document.getElementById('ajout').disabled = false; } } var delRowList = function(btn2) { var delbtn = document.getElementById('sellTable'); delbtn.deleteRow(btn2.parentNode.rowIndex); } var setupListeners = function() { var btn = document.getElementById('ajout'); btn.addEventListener('click', addShopList); } window.addEventListener('load', setupListeners);
 <select id="shopList" onlick="summ()" class="form-select form-select-lg mb-3"> <option selected disabled="disabled"> Liste Des Produits</option> <optgroup label="Femme"> <option value="40" name="PullVegeta2"> Top Femme Colle V </optgroup> <optgroup label="Homme"> <option value="35" name="PullVegeta3">Pull Homme OpenMinded <option value="30" name="PullVegeta">Pull Homme Vegeta </optgroup> </select> <input type="text" id="qte" placeholder="Quantité" onkeyup="emptyQte()" onkeypress="return (event.charCode == 8 || event.charCode == 0)? null: event.charCode >= 48 && event.charCode <= 57" required/> <input type="button" value="Ajouter" id="ajout" disabled> <table id="sellTable" class="table"> <thead> <tr> <th scope="col">Nom Produit</th> <th scope="col">Quantité</th> <th scope="col">Prix Unitaire</th> <th scope="col">Total Produit</th> <th scope="col">Action</th> </tr> </thead> <tbody> </tbody> <tfooter> <td colspan="3">Somme Total:</td> <td id="totalprod"> DT</td> <td> <button>Paiement</button></td> </tfooter> </table>

我建议不要使用parseFloat ,而是使用Number()构造函数,对于空String ,它返回0而不是NaN

const total = [...document.getElementsByClassName('subTotal')]
  .map(el=>el.value)
  .reduce((a, v) => a + Number(v), 0);

有关Number()parseFloat()的不同结果,请参阅此代码段:

 const testValues = ['', null, undefined]; for (const value of testValues) { console.log(`Number(${value}) returns: ${Number(value)}`); console.log(`parseFloat(${value}) returns: ${parseFloat(value)}`); }

您的parseFloat function 可能在某个时候返回NaN

 let total = 0 for(const subTotalElem of document.getElementsByClassName('subTotal')) { const subTotal = Number.parseFloat(subTotalElem.value) if(Number.isNaN(subTotal)) { console.warn('Subtotal is not a number: ' + subTotalElem.value) } else { total += subTotal } } console.log('Total: ' + total)
 <table> <tbody> <tr> <td>Parseable</td> <td><input disabled class="subTotal" value="42" /></td> </tr> <tr> <td>Parseable</td> <td><input disabled class="subTotal" value="42.00" /></td> </tr> <tr> <td>Parseable</td> <td><input disabled class="subTotal" value="42,00" /></td> </tr> <tr> <td>Not Parseable</td> <td><input disabled class="subTotal" value="$42.00" /></td> </tr> <tr> <td>Not Parseable</td> <td><input disabled class="subTotal" value="" /></td> </tr> </tbody> </table>

我修好了,对不起是我的错。 我将我的第一个 td 的类名放在行中,其中包含产品名称而不是价格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM