如何从动态创建的表传递参数

问题描述 投票:0回答:1

下面的代码有效,但我总是得到表中最后一个按钮的值。我如何从每个按钮记录正确的表计数。 console.log 总是给出最后一个按钮的值。

<!DOCTYPE html>
<html>
<head>
  <style>
    table,
    td {
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <p>Click "add row" to add several new rows, then click "show count"</p>
  <button type="button" onclick="addTr()">add row</button>
  <table id="myTable">
  </table>

  <script>
    function showCount(trCount) {
      console.log("trCount = " + trCount);
    }

    var trCount = 0;

    function addTr() {
      var table = document.getElementById("myTable");
      var tr = table.insertRow(trCount);
      var td0 = tr.insertCell(0);
      td0.innerHTML = (trCount + 1);
      var td1 = tr.insertCell(1);
      td1.innerHTML = '<input type="button" value="Show Count" onclick="showCount(trCount)">';
      trCount++;
    }
  </script>
</body>
</html>

javascript html-table
1个回答
0
投票

输入此代码:

function showCount(trCount){
            console.log("trCount = "+trCount);
        }

        var trCount = 1;
        function addTr() {
            var table = document.getElementById("myTable");
            var tr = table.insertRow(trCount-1);
            var td0 = tr.insertCell(0);
            td0.innerHTML = trCount;
            var td1 = tr.insertCell(1);
            // Pass trCount as an argument to showCount
            td1.innerHTML = '<input type="button" value="Show Count" onclick="showCount(' + trCount + ')">';
            trCount++;
        }
© www.soinside.com 2019 - 2024. All rights reserved.