首页 > 解决方案 > How to change specific values in a table created in javascript by pressing a button

问题描述

Does anyone here know how I can change the value of "list4" when I have created a HTML table like so:

var obj = { list1, list2, list3, list4, list5 };
var newArray = [];

  Object.keys(obj).forEach( (o) => newArray.push(obj[o]));

newArray.forEach(function(items) {
var row = document.createElement("tr");
    items.forEach(function(item) {
var cell = document.createElement("td");
    cell.textContent = item;
    row.appendChild(cell);
});
 table.appendChild(row);
}); 

I have extracted the 5 list elements out of a larger array by using this method:

var list1 = myArray.map(a => a.list1);
var list2 = myArray.map(a => a.list2);
var list3 = myArray.map(a => a.list3);
var list4 = myArray.map(a => a.list4);
var list5 = myArray.map(a => a.list5);

And I would like to change the value of all of the list elements in "list 4" to the existing values divided by 2.2046:

I have made a for-loop and changed the values to the new values:

var newValues = myArray.map(a => a.list4);

for (var i = 0; i < newValues.length; i++) {
newValues[i] = (newValues[i]/2.2046).toFixed(1);
}

Does anyone know how I can incorporate the last code so that I, by pressing a button with the id="metric", can make all the existing values change to the new values? I thinking maybe innterHTML could help, but I do not know how to get the specific values of list4.. Thank you for any help!

Bonus:
I have tried everything but have not succeeded in turning a string of "5' 6\"" into actual numbers as I also have to change these to metric values, possible anyone here knows?:) Thank you!

标签: javascripthtmlarraysloopshtml-table

解决方案


cell在与列表相同的范围内创建一个元素数组。这样,您就可以cell[0].textContent = value随时随地编写一些东西。

在新函数中单独更新 HTML。使用 清除 HTML remove(),然后使用.appendChild(cell[0])添加新值进行更新。

至于将字符串更改为数字,这里有一个想法:

let number = "5' 6\"";
let div = document.getElementById("test");
let decimalValue = imperialToDecimal(number);

div.innerHTML = number + " becomes " + decimalValue;

function imperialToDecimal(measurement) {
  let indxFeet = measurement.indexOf("'");
  let indxInches = measurement.indexOf("\"");
  let feet = measurement.substring(0, indxFeet);
  let inches = measurement.substring(indxFeet + 1, indxInches);
  return footAndInchToMeter(feet, inches);
}

function footAndInchToMeter(feet, inches) {
  feet = feet/3.2808;
  inches = inches/39.370;
  return feet + inches;
}
<div id="test"></div>

'这是没有或符号时不包含更正的基本代码"(但你可以弄清楚,我敢肯定:)。


推荐阅读