使用JavaScript或CSS添加OnClick事件

时间:2013-12-18 11:30:20

标签: javascript jquery html css

我有一个HTML表格:

    <table id="cust">
        <tr>
            <th>UserName</th>
            <th>Password</th>       
        </tr>       
            <script type="text/javascript">addRows();</script>
        </table>

我在JS中有函数将Rows插入此表。例如:

function addRows() {
  // Get a reference to the table   
  var table = document.getElementById("cust");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell0 = row.insertCell(0);
  var cell1 = row.insertCell(1);
  cell0.innerHTML = "ilan";
  cell1.innerHTML = "11111";
}

但我想要插入到表中的每一行都将使用onClick事件:

<tr onclick="window.document.location='Accounts.html';">

我该怎么做?

谢谢!!

2 个答案:

答案 0 :(得分:1)

你可以使用它 -

  

row.setAttribute( “点击”, “window.document.location = 'Accounts.html'”);

   function addRows() {
      // Get a reference to the table   
      var table = document.getElementById("cust");
      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);
      row.setAttribute("onclick","window.document.location='Accounts.html'");
      var cell0 = row.insertCell(0);
      var cell1 = row.insertCell(1);
      cell0.innerHTML = "ilan";
      cell1.innerHTML = "11111";
    }

答案 1 :(得分:0)

由于您没有使用任何jQuery构造,因此在行元素

中添加onclick处理程序
function addRows() {
    // Get a reference to the table   
    var table = document.getElementById("cust");
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.onclick = rowClick
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);
    cell0.innerHTML = "ilan";
    cell1.innerHTML = "11111";
}

function rowClick() {
    window.document.location = 'Accounts.html';
}

如果您想拥有不同的目标位置,那么

function addRows() {
    // Get a reference to the table   
    var table = document.getElementById("cust");
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.onclick=function(){
        window.document.location='Accounts.html';
    }
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);
    cell0.innerHTML = "ilan";
    cell1.innerHTML = "11111";
}