简体   繁体   English

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

[英]Hide parent TR if link has no href?

I current have this: 我目前有这个:

<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>

I need some javascript that will: 我需要一些JavaScript,它将:
if <a> has no href (href="") then hide the TR that wraps it. 如果<a>没有href(href =“”),则隐藏包装它的TR。

How do I achieve this using javascript? 如何使用javascript实现此目的?

You can use attribute equals selector for getting a tag with href="" and then get tr by closest() 您可以使用属性等于选择器来获取带有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> 


Or you can use :has() or has() and attribute equals selector . 或者,您可以使用:has()has()属性equals selector

 $('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> 

FYI : 仅供参考:

If you want to select a tag without href attribute then you can use :not() selector, eg: 如果要选择没有href属性a标签,则可以使用:not()选择器,例如:

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

If you want to check for only href="" 如果您只想检查href =“”

simply try 只需尝试

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

or 要么

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

If you also want to check for only href="" or no href attribute given 如果您也只想检查href =“”或未提供href属性

simply try 只需尝试

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

or 要么

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

https://jsfiddle.net/现在看看它的工作情况,请检查

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

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