繁体   English   中英

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

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

我目前有这个:

<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()属性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> 

仅供参考:

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

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

如果您只想检查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();

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

暂无
暂无

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

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