0

我有一个表格,当将链接添加到任何单元格时,它可以使整行可点击。我想做的是将此脚本添加到页面上的多个表中。问题是该脚本只能与一个表一起使用,因为它只能与 id 一起使用,而不能与 class css 一起使用。如何添加多个表 ID?

      window.onload = function(){
      ConvertRowsToLinks("results-table"); //My table id
      // ConvertRowToLinks("results-table", "results-table2");
      // I would like to add results-table2, results-table3 etc...

  }

  function ConvertRowsToLinks(xTableId){

    var rows = document.getElementById(xTableId).getElementsByTagName("tr");

    for(i=0;i<rows.length;i++){
      var link = rows[i].getElementsByTagName("a")
      if(link.length == 1){
        rows[i].onclick = new Function("document.location.href='" + link[0].href + "'");
        rows[i].onmouseover = new Function("this.className='highlight'");
        rows[i].onmouseout = new Function("this.className=''");
      }
    }


    ConvertSideRowsToLinks("sidebar-table");
  }

  function ConvertSideRowsToLinks(xTableId){

    var rows = document.getElementById(xTableId).getElementsByTagName("tr");

    for(i=0;i<rows.length;i++){
      var link = rows[i].getElementsByTagName("a")
      if(link.length == 1){
        rows[i].onclick = new Function("document.location.href='" + link[0].href + "'");
        rows[i].onmouseover = new Function("this.className='highlight'");
        rows[i].onmouseout = new Function("this.className=''");
      }
    }

  }
4

3 回答 3

0

您也可以通过这种方式对参数进行切片,您可以根据需要传递任意数量的 id,并且您不必创建数组显式:

  function ConvertSideRowsToLinks()
  {
    var ids = Array.prototype.slice.call(arguments)
    for (var key in ids)
    {
        var table =  document.getElementById(ids[key])
        var rows =table.getElementsByTagName("tr");

        for(i=0;i<rows.length;i++){
          var link = rows[i].getElementsByTagName("a")
          if(link.length == 1){
            rows[i].onclick = new Function("document.location.href='" + link[0].href + "'");
            rows[i].onmouseover = new Function("this.className='highlight'");
            rows[i].onmouseout = new Function("this.className=''");
        }
      }
    }
  }
于 2012-09-12T15:40:57.790 回答
0

使用类作为:

//Html code
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

// access like
var elements = document.getElementsByClassName("test");
于 2012-09-12T15:35:04.263 回答
0

您可以传递一个数组并对其进行迭代:

function ConvertTablesRowsToLinks(tableIds){
  tableIds.forEach( ConvertRowsToLinks);

}

function ConvertRowsToLinks(xTableId){
    var i; // variable i should be declared otherwise is leaking to global namespace.
    var rows = document.getElementById(xTableId).getElementsByTagName("tr");
    for(i=0;i<rows.length;i++){
      var link = rows[i].getElementsByTagName("a")
      if(link.length == 1){
      rows[i].onclick = new Function("document.location.href='" + link[0].href + "'");
      rows[i].onmouseover = new Function("this.className='highlight'");
      rows[i].onmouseout = new Function("this.className=''");
    }
  }
于 2012-09-12T15:37:12.323 回答