繁体   English   中英

如何在JQuery / Javascript中访问来自数据表单元格的复杂对象

[英]How to access a complex object comming from a datatable cell in JQuery/Javascript

我有一个具有以下变量的(Microsoft MVC视图的)视图模型的Record对象的列表:

Variable1 of string type
Variable2 of int type
... 

我有一个记录表的剃须刀视图,如下所示:

<table id="MyTable">
    <thead>
        <tr>
            <th class="col1" id="Column1">Column1</th>
            <th class="col2" id="Column2">Column2</th>
            <th class="col3" id="Column3">Column3</th>
        </tr>
    </thead>
    <tbody>
        @foreach (Record currentRecord in ListOfRecords)            {
            <tr>
                <td class="col1">X</td>
                <td class="col2">Y</td>
                <td class="col3">@currentRecord</td>
            </tr>
        }
    </tbody>
</table>

然后在我的JQuery中:

$(document).ready(function () {

    function displayData(datainput) {
        alert(datainput.Variable1)
    }

    var oTable = $('#MyTable').DataTable({
        "oLanguage": { "sSearch": "Search all columns:" },
        "sScrollY": "200px",
        "bPaginate": false
    });

    $('#MyTable tbody').on('click', 'td', function () {
        var rowIndex = oTable.cell(this).index().row;
        var theData = oTable.cell(rowIndex,2).data();
        displayData(theData)
    });
});

想法是显示用户单击的特定行的记录对象中的Variable1作为警报文本,特别是在displayData函数中。 但是我无法在displayData函数中找到该变量。 警报显示未定义,而不是Variable1的值。 有需要传递参数的特定方法吗? 我是JavaScript / JQuery / Razor视图的新手,所以请您提供帮助。

谢谢。

对于那些感兴趣的人,可以使用Json使其工作,首先在视图中对其进行编码:

<tbody>
    @foreach (Record currentRecord in ListOfRecords)            {
        <tr>
            <td class="col1">X</td>
            <td class="col2">Y</td>
            <td class="col3">@Html.Raw(Json.Encode(currentRecord))</td>
        </tr>
    }
</tbody>

然后在脚本中解析它:

$('#MyTable tbody').on('click', 'td', function () {
    var rowIndex = oTable.cell(this).index().row;
    var theData = jQuery.parseJSON(oTable.cell(rowIndex,2).data());
    displayData(theData)
});

暂无
暂无

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

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