on元素在td元素上返回firstcolumn值和header值

时间:2016-03-02 01:52:13

标签: javascript jquery datatable onclick

我有TD元素onlick =“myfunction()”。我希望该函数能够使用表中的其他值创建自定义location.href。

function myfunction( elem ) {
 var table = $('#horo').DataTable();
 var idx = table.cell(elem).index().column;
 var ColumnHeader = table.column(idx).header();
 var FirstColumnValue = X;
 location.href = "Page.cshtml?ID=" + ColumnHeader + "?Name=" + FirstColumnValue;
}

每次它一直告诉我Page.cshtml?ID = Undefined

这个表就像这样调用

          <table class="horo" width="1235px" style="border-style: solid; border-width: thin">
        <thead>
            <tr>
                @foreach(DataColumn col in table.Columns)
                {
                    <th class="cedule2">@col.ColumnName</th>
                }
            </tr>
        </thead>
        <tbody>
            @foreach(DataRow row in table.Rows)
            {
                <tr>
                    @foreach(DataColumn col in table.Columns)
                    {
                        <td  onclick="myfunction(this)" onmouseover="" style="width: 154px; border: 1px solid black">@row[col.ColumnName]<br></td>
                    }
                </tr>
            }
        </tbody>
    </table>

这是我使用Razor创建表格的方式

DataTable table = new DataTable();

for(int i = 0; i <= data.Count(); i++){
    table.Columns.Add(i.ToString(), typeof(string));

}
foreach(var col in data.First().Columns){
    var val = new List<string>();
    val.Add(col);

    foreach(var rec in data){
        val.Add(rec[col].ToString());

    }

    table.Rows.Add(val.ToArray());

}

非常感谢你的帮助。真的很感激

1 个答案:

答案 0 :(得分:1)

在您的情况下,

this是一个窗口对象,您需要再次调用用于实例化datatables的元素,假设:

function myfunction( elem ) {
  // assume you call datatable with 
  // this element = $('table#myTable')
  // then use that
  var table = $('table#myTable').DataTable();
  // `this` inside .cell(this) should change to current clicked element
  // and must be passed as function args
  var idx = table.cell(elem).index().column;
  var ColumnHeader = table.column(idx).header();
  var FirstColumnValue = Noclue;
  location.href = "Page.cshtml?ID=" + ColumnHeader + "Name=" + FirstColumnValue;
}

所以TD元素应该是:

<td onclick="myfunction(this)">......</td>

不是使用内联脚本直接调用函数,而是使用jQuery .on

var table = $('table#myTable').DataTable();

$('table#myTable tbody').on( 'click', 'td', function () { 
  var idx = table.cell(this).index().column;
  var ColumnHeader = table.column(idx).header();
  var FirstColumnValue = Noclue;
  location.href = "Page.cshtml?ID=" + ColumnHeader + "Name=" + FirstColumnValue;
});