使用Jquery可以查找父表、表或td

Use Jquery to find the parent table, of a table, of a td

本文关键字:表或 td 查找 Jquery 使用      更新时间:2023-09-26

我正在自定义Sage CRM,因此我无法控制所编写的HTML,也无法将ID或类添加到CRM所显示的表布局中。我想根据用户对选择下拉列表的选择来隐藏更高级别(而不是顶级)的表。我只能将jQuery选择器挂接到要隐藏的表中的表的标题行上。

DOM类似于:

//Lots of other table structures above this in the DOM....
<table>  <---- this is the table I want to show or hide based on the users selection
  <tbody>
    <tr>
     <td>
       <table>
         <tbody>
           <tr>
             <td class="PANEREPEAT">  <---- this is the node I can get selector to
                 Valuation information
////

所以我做了以下客户端javascript:

    var val_information_screen;
    $('.PANEREPEAT').filter(function () {
        //Find the valuation information screen
        return $(this).text() == 'Valuation information';
    }).each(function () { //iterate through all of these (there should only be one!)
        val_information_screen = $(this);
    });
    var sel_ofee_type = $('#ofee_type');
    if (sel_ofee_type.val() == '006') {
        val_information_screen.closest('table').parents("table:first").show();
    } else {
        val_information_screen.closest('table').parents("table:first").hide();
    }

它确实有效,只是不是特别漂亮。下面是我真正讨厌的部分。有没有更好的方法可以使用jQuery遍历DOM?

val_information_screen.closest('table').parents("table:first").show();
val_information_screen.closest('table').parents("table:first").hide();

如果你确定它有固定的结构,那么你可以使用这个,

$(td-selector).parents("table").eq(1).hide();

在您的情况下,

val_information_screen.parents("table").eq(1).hide();

如果您的DOM(特别是从您想要隐藏的表开始,直到您作为选择器的td)基本上是固定的,那么可以使用下面的选择器。

$('#element').parents('table').eq(1)