如果链接没有 href,则隐藏父 TR

Hide parent TR if link has no href?

本文关键字:隐藏 TR href 链接 如果      更新时间:2023-09-26

我目前有这个:

<table>
    <tbody>
        <tr>
            <td>
            <a href="http://www.google.com">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="http://www.google.com">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="">Visit Website</a>
            </td>
        </tr>
    </tbody>
</table>

我需要一些 JavaScript 来:
如果<a>没有 href (href=") 则隐藏包装它的 TR。

如何使用javascript实现这一点?

您可以使用

属性等于选择器来获取带有href="" a标签,然后通过closest()获取tr

$('a[href=""]').closest('tr').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td>
            <a href="http://www.google.com">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="http://www.google.com">Visit Website</a>
            </td>
        </tr>
        <tr>
            <td>
            <a href="">Visit Website</a>
            </td>
        </tr>
    </tbody>
</table>


或者,您可以使用:has()has()属性等于选择器

$('tr:has(a[href=""])').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        <a href="http://www.google.com">Visit Website</a>
      </td>
    </tr>
    <tr>
      <td>
        <a href="">Visit Website</a>
      </td>
    </tr>
    <tr>
      <td>
        <a href="http://www.google.com">Visit Website</a>
      </td>
    </tr>
    <tr>
      <td>
        <a href="">Visit Website</a>
      </td>
    </tr>
  </tbody>
</table>


仅供参考:

如果要选择没有href属性a标签,则可以使用:not()选择器,例如:

$('a[href=""],a:not(a[href])').closest('tr').hide();
https://jsfiddle.net/看看

这个现在它的工作,请检查

如果你只想检查 href="

只需尝试

$('a[href=""]').parent().parent().hide();

$('a[href=""]').closest("tr").hide();

如果您还想仅检查 href=" 或未给出 href 属性

只需尝试

$('a[href=""],a:not([href])').parent().parent().hide();

$('a[href=""],a:not([href])').closest("tr").hide();