简体   繁体   English

使用JavaScript或CSS添加OnClick事件

[英]Add OnClick Event with JavaScript or CSS

I have a table in HTML: 我有一个HTML表:

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

and I have function in JS that insert Rows to this table. 并且我在JS中有将行插入此表的功能。 for example: 例如:

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";
}

but I want that every row that insert to the table, will be with onClick event like that: 但我希望插入到表中的每一行都具有如下onClick事件:

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

how can I do that? 我怎样才能做到这一点?

thank you !! 谢谢 !!

You can use this- 您可以使用此-

row.setAttribute("onclick","window.document.location='Accounts.html'"); 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";
    }

Since you are not using any jQuery constructs add a onlick handler to the row element 由于您未使用任何jQuery构造,因此在行元素中添加了onlick处理程序

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';
}

If you want to have different target locations then 如果您想拥有不同的目标位置,那么

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";
}

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

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