如何使用 javascript 在 laravel blade 中以编程方式在 table 中添加一行

how to add a row in the table programmatically in the laravel blade using javascript

我是 laravel 的新手,我正在尝试在其中创建一个包含底部的表单,在表单的 table 中创建新行。 这是我的脚本:

function myFunction() {
    var table = document.getElementById("AcademicDegreeTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
    cell3.innerHTML = "NEW CELL2";
    cell4.innerHTML = "NEW CELL2";
}

和:

<button class="button" onclick="myFunction()">Try it</button>

但是当我点击这个按钮时,新行会出现一小段时间,然后当页面重新加载时,新行就会消失。

路线:

Route::get('/form' , 'FormController@index')->name('form');

控制器:

public function index()
{
    return view('form');
}

您可以设置 cookies 或将行计数值放入 session 否则会有 Web Storage html 中的概念你也可以使用它。

如果您的按钮在表单中,则默认行为是单击按钮提交表单。为了防止它,onclick 处理程序必须 return false:

<button class="button" onclick="return myFunction()">

function myFunction() {
  //...
  return false;
}

无论如何,你最好使用 jQuery。