函数的多个参数

时间:2012-09-12 15:27:33

标签: javascript function arguments getelementbyid

我有一个表格,当链接添加到任何单元格时,它会使整行可以点击。我想要做的是将此脚本添加到页面上的多个表中。问题是脚本只能用于一个表,因为它只能用于id而不能用于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=''");
      }
    }

  }

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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=''");
    }
  }

答案 2 :(得分:0)

你也可以这样切片参数你可以传递任意数量的id,而不必创建数组explicite:

  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=''");
        }
      }
    }
  }