【问题标题】:How to find td value with same tr's ID in jQuery如何在jQuery中找到具有相同tr ID的td值
【发布时间】:2017-04-22 21:29:36
【问题描述】:

我有一个 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);
        });
    });

但我无法获取此 ID。

【问题讨论】:

  • 您应该使用class 而不是id。在你的tr 上放一个类,并在这个类上定义一个事件监听器。
  • 你能给我举个例子吗?

标签: jquery foreach html-table


【解决方案1】:

如果您能够在您的tr 上使用class 而不是id,这就是解决方案。

首先,替换这个:

<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);
  })
  
});

【讨论】:

  • 没问题!祝你编码愉快!
【解决方案2】:

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

$(document).ready(function () {

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

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

【讨论】:

  • 这个td被隐藏了,所以我不能点击这个!我试试你的代码,但我没有得到任何答案:(
  • 您将在整个 tds 上定义事件。所以点击哪个 td 并不重要。
  • 如何在 tds 上定义事件??
  • $(document).ready(function () { $("#myTable").find('td').each({ $(this).click(function () { //这里有错误“标识符的关键字使用无效”。 var currentRow = $(this).closest("tr"); var col1 = currentRow.find("td:eq(4)").text( ); 警报(col1); }); }); });
  • 不幸的是它不起作用!不过感谢您的帮助;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
相关资源
最近更新 更多