如何使用 JavaScript 动态更改 HTML 表格内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27859976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:47:34  来源:igfitidea点击:

How to dynamically change HTML table content using JavaScript

javascripthtml

提问by Murad Elboudy

var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
  var table = document.getElementById('insertfirsttable'),
    itemType = prompt("Enter the item name"),
    filling1 = prompt("Enter the filling"),
    filling2 = prompt("Enter the filling"),
    filling3 = prompt("Enter the filling"),
    stock = prompt("Enter the amount in stock"),
    minimum_Stock = prompt("Enter the minimum amount of stock");

  for (var r = 0; r < 1; r += 1) {
    var x = document.getElementById('insertfirsttable').insertRow(r);
    for (var c = 0; c < 10; c += 1) {
      var y = x.insertCell(c);
    }

    table.rows[r].cells[0].innerHTML = itemType;
    table.rows[r].cells[1].innerHTML = filling1;
    table.rows[r].cells[2].innerHTML = filling2;
    table.rows[r].cells[3].innerHTML = filling3;
    table.rows[r].cells[4].innerHTML = stock;
    table.rows[r].cells[5].innerHTML = minimum_Stock;
    table.rows[r].cells[9].innerHTML = '<button id="sellbtn" style="width:102px; height: 25px; font-size:18px; cursor:pointer">Sell</button>';
    table.rows[r].cells[9].style.width = "100px";
    var sellBtn = document.getElementById("sellbtn");
  }
  //problem is here i guess
  sellBtn.addEventListener("click", function() {
    var sell = prompt("Enter the stock amount you're selling"),
      total = stock - sell;
    for (var t = 0; t < table; t += 1) {
      for (var c = 0; c < table.cells.length; c += 1) {}
      table.rows[t].cells[4].innerHTML = total;

    }
  });
});
body {
  margin: 0;
  padding: 0;
  background-color: #E6E6E6;
  font-size: 20px;
}
table {
  border-spacing: 1px;
  width: 100%;
}
th {
  padding: 1px;
}
#firsttablediv {
  width: 100%;
}
#firsttable {
  color: white;
  background-color: green;
}
#insertitem {
  width: 100%;
  padding: 2px;
  font-size: 20px;
  cursor: pointer;
}
#insertfirsttable > tr {
  background-color: #31B404;
}
<html>

<body>
  <div id="firsttablediv">
    <table id="firsttable" border="1">
      <thead>
        <th>Item</th>
        <th colspan="3">Filling</th>
        <th>Storage</th>
        <th>Minimum Stock</th>
        <th>Last Inventory</th>
        <th>Sell</th>
        <th>Last Month Inventory</th>
        <th colspan="2">
          <button id="insertitem">New Item</button>
        </th>
      </thead>
      <tbody id="insertfirsttable">
      </tbody>
    </table>
  </div>

Guys I'm writing an application for my father's shop. He wants an application to manage his items and such, anyways, after you click on the insert item button and input the details. The item is then put in a row with each detail in it's respective cell, also a button appears within that row called 'Sell' in which if an item has been sold you press on it and it asks you how many of that item you have sold? you type the number and then enter and it should subtract the stock number from that number and put in the new number in the stock cell of that row but i can't seem to know how to do it.

伙计们,我正在为我父亲的商店写申请。他想要一个应用程序来管理他的项目等,无论如何,在您单击插入项目按钮并输入详细信息之后。然后将该项目与每个详细信息放在相应单元格中的一行中,该行中还会出现一个名为“出售”的按钮,如果该项目已售出,您按下它并询问您有多少该项目卖?您输入数字然后输入,它应该从该数字中减去股票编号,然后将新编号放入该行的股票单元格中,但我似乎不知道该怎么做。

回答by Mahdi Jazini

JavaScript Area:

JavaScript 区:

document.getElementById('test1').innerHTML = 'Night';

HTML Area:

HTML 区域:

<td id="test1">Day</td>

The JavaScript code changes the Dayto Night

JavaScript 代码将白天更改为黑夜

Also the Nightvalue can be replaced with a HTML code.

另外,值可以用替换HTML代码

For example <b>Night</b>

例如 <b>Night</b>

Source

来源

回答by Si Kelly

There are a few things you can improve here. Firstly you don't need a for-loop to execute something only once:

你可以在这里改进一些东西。首先,您不需要 for 循环只执行一次:

for (var r = 0; r < 1; r += 1) {

Get rid of this loop.

摆脱这个循环。

So how do you get hold of the row that has just been inserted? Luckily Table.insertRow() returns a reference to the row that got inserted. So you can do:

那么如何获取刚刚插入的行呢?幸运的是 Table.insertRow() 返回对插入行的引用。所以你可以这样做:

var row = document.getElementById('insertfirsttable').insertRow();
row.cells[0].innerHTML = itemType;
//and so on

Also note that you don't need to pass an index to insertRow(), since a row automatically gets added at the end of the table. If you want it at the beginning, use insertRow(0). See here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement.insertRow/

另请注意,您不需要将索引传递给insertRow(),因为会在表的末尾自动添加一行。如果您希望在开头使用,请使用 insertRow(0)。请参阅此处:https: //developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement.insertRow/

As James pointed out in the comments, you can't give all the buttons the same id. In that case how would you get a reference to the button to add the listener? Better create the element using document.createElement()instead, then you get a reference returned.

正如 James 在评论中指出的那样,您不能为所有按钮提供相同的 ID。在这种情况下,您将如何获得对按钮的引用以添加侦听器?最好使用document.createElement()代替创建元素,然后你会得到一个返回的引用。

var button = document.createElement("button");
row.cells[9].appendChild(button);

button.addEventListener("click", function(){
   var sell = prompt("Enter the stock amount you're selling"),
   total = stock - sell;

   // we still have a reference to row here because we are in a closure.
   row.cells[4].innerHTML = total;
});

回答by Si Kelly

Instead of using 'stock'where you subtract from the sell value, get the 'stock' element from the row based on the ID, convert to number and then subtract.

不要使用'stock'从卖出值中减去的位置,而是从基于 ID 的行中获取 'stock' 元素,转换为数字然后减去。

And there's something called JQuery for stuff like this. You could give it a try. Specifically the .on() methodwill work here. When you add a button dynamically usually the event-handlers are not hooked on to the new button. This will cause your code to stop working. So use the JQuery on() method instead.

对于这样的东西,有一种叫做 JQuery 的东西。你可以试一试。特别是.on() 方法将在这里工作。当您动态添加按钮时,事件处理程序通常不会连接到新按钮。这将导致您的代码停止工作。因此,请改用 JQuery on() 方法。

Also ID's are supposed to be unique. So create unique ID values for your buttons may be using the index.

ID 也应该是唯一的。因此为您的按钮创建唯一的 ID 值可能会使用索引。