如何在jQuery中找到具有相同tr ID的td值

时间:2017-04-22 21:29:37

标签: jquery foreach html-table

我有一个HTML表,其中的行使用foreach循环,如下所示:

@foreach (var item in Model) {
        <tr id="tr1" class="text-center" onClick="HighLightTR(this, '7ED1E6', 'cc3333');" >
            <td>
                @Html.DisplayFor(modelItem => item.StartDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.InternalMedicineCode)
            </td>
            <td class="text-center">
                @Html.DisplayFor(modelItem => item.Tbl_InternalMedicine.InternalMedicineName)
            </td>
            <td id="td2">
                @Html.DisplayFor(modelItem => item.Dose)
            </td>
            <td class="hidden" id="td1">
                @Html.DisplayFor(modelItem=>item.IdTherapyRegistration)
            </td>

当我点击一行时,我想提醒隐藏的单元格的值,其ID为td1。我不知道如何用jQuery做到这一点。我的jQuery函数代码是:

$(document).ready(function () {

        $("#myTable").on('click', 'tr', function () {
            var currentRow = $(this).closest("tr");

            var col1 = currentRow.find("td:eq(4)").text();
            alert(col1);
        });
    });

但我无法得到这个身份。

2 个答案:

答案 0 :(得分:0)

你应该在td上定义事件而不是tr。

&#13;
&#13;
$(document).ready(function () {

        $("#myTable tr").(function (){
            var currentRow = $(this);

            var col1 = currentRow.find("td:eq(4)").text();
            alert(col1);
        });
    });
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您可以在class上使用id代替tr,则可以使用以下解决方案。

首先,替换它:

<tr id="tr1" class="text-center" onClick="HighLightTR(this, '7ED1E6', 'cc3333');" >

由此:

<tr class="text-center tr-clickable" onClick="HighLightTR(this, '7ED1E6', 'cc3333');" >

然后,像这样更新你的jQuery函数:

$(document).ready(function () {

  $(".tr-clickable").on("click", function() {
    var currentRow = $(this);
    var col1 = currentRow.find("td:eq(4)").text();
    
    alert(col1);
  })
  
});