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