简体   繁体   English

JavaScript - 在 HTML 表中动态添加表行

[英]JavaScript - Dynamically add table rows in HTML table

I have the following script by which I want to achieve to dynamically add rows in an HTML table on my website:我有以下脚本,我想通过它在我的网站上的 HTML 表中动态添加行:

<script>
var globalIterationVariable = 0;
document.onload = $globalIterationVariable = 1;
$('document').ready(function() {
  $('.add_another').click(function() {
      var globalIterationVariable;
      var newRowVariable = '<tr><td><center><input name="nazovPolozky';
      newRowVariable.append(String($globalIterationVariable));
      newRowVariable.append(' type="text"></center></td> <td><center><input name="pocetPolozky');
      newRowVariable.append(String($globalIterationVariable));
      newRowVariable.append('" type="number" step="1" min="1"></center></td> <td><center><input name="jednotkovaCenaPolozky');
      newRowVariable.append(String($globalIterationVariable));
      newRowVariable.append('" type="number" step="0.01" min="0.01"></center></td></tr>');
      alert(String(newRowVariable));
      $("#tbl").append(String(newRowVariable));
      globalIterationVariable++
   });
});
</script>

This script though gives me the following error:这个脚本虽然给了我以下错误:

Uncaught TypeError: newRowVariable.append is not a function

Can anybody, please, help me to get this script working?任何人都可以请帮我让这个脚本工作吗?

Thank you.谢谢你。

PS: This script is launched once I press a specific button on my website which has a class='button add_another' PS:一旦我在我的网站上按下具有 class='button add_another' 的特定按钮,就会启动此脚本

You should define newRowVariable as a DOM element ->您应该将newRowVariable定义为 DOM 元素 ->

const newRowVariable = document.createElement('tr')

Then append the content (your string) to it ->然后 append 的内容(你的字符串)到它 - >

newRowVariable.innerHTML = `<td><center><input name="nazovPolozky ${$globalIterationVariable}" type="text"></center></td>

Notice I use `` and not '' or "", it's because you can use javascript variables inside a string like that ->注意我使用 `` 而不是 '' 或 "",这是因为你可以在这样的字符串中使用 javascript 变量 ->

const text = "World"
const superString = `Hello ${text}`
// a console.log(superString) will return 'Hello World'

Jquery might be usefull when you are a complete begginner, but you'll figure out soon that it's way simpler to use pure javascript;) Jquery 在您完全是初学者时可能会很有用,但您很快就会发现使用纯 javascript 会更简单;)

This is a string这是一个字符串

 var newRowVariable = '<tr><td><center><input name="nazovPolozky';

This is a jQuery object这是 jQuery object

 var newRowVariable = $('<tr><td><center><input name="nazovPolozky');

This is how you append a string to a string这就是你如何 append 一个字符串到一个字符串

 var newRowVariable = '<tr><td><center><input name="nazovPolozky';
 newRowVariable += "/></td></tr>";

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

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