如果 URL 为空,则隐藏 li 标记



我正在使用以下内容向用户显示Facebook和Twitter链接。

<ul class="list-inline">
  <li style="padding-right:20px;">
    <a href="https://{{channel.facebook_page}}" rel="nofollow" target="_blank" title="{{channel.channel_name}} On FaceBook"><i aria-hidden="true" class="fa fa-facebook fa-2x" style='color:#ee6f00'></i></a>
  </li>
   <li>
   <a href="https://{{channel.twitter_page}}" rel="nofollow" target="_blank" title="{{channel.channel_name}} On Twitter"><i aria-hidden="true" class="fa fa-twitter fa-2x" style='color:#ee6f00'></i></a>
   </li>
</ul>

有时我的网站用户没有Facebook或Twitter帐户。那么,如果https://后的href值为空,有没有办法隐藏li。换句话说,如果我{{channel.facebook_page}}是空白的,请隐藏th li.

脚本将是一个明显的解决方案,尽管还有一个。

使用 CSS 属性选择器 [attribute='value'] ,然后执行以下操作。

a[href='https://'] {
  display: none;
}

而对于li上的填充设置,请改用锚a上的margin,您可以单独使用CSS解决此问题,并获得与隐藏li相同的视觉效果。

不知道你用什么框架来模板化,我会试一试,根据你个人资料中的标签猜测 Angular。

您可以将 Angular's 与 ng-if 一起使用,以显示元素的评估结果是否真实

<li 
  ng-if="channel.facebook_page"
  style="padding-right:20px;">
    <a href="https://{{channel.facebook_page}}" rel="nofollow" target="_blank" title="{{channel.channel_name}} On FaceBook"><i aria-hidden="true" class="fa fa-facebook fa-2x" style='color:#ee6f00'></i></a>
</li>

你可以做@LGSon在他的CSS中使用的a[href='https://']选择器,但在你的javascript中使用它,然后获取parentElement并将其设置为display: none

document.querySelectorAll('[href="https://"]').forEach(function(el) {
    el.parentElement.style.display = 'none';
});
<ul class="list-inline">
  <li style="padding-right:20px;">
    <a href="https://" rel="nofollow" target="_blank" title="{{channel.channel_name}} On FaceBook"><i aria-hidden="true" class="fa fa-facebook fa-2x" style='color:#ee6f00'></i> Facebook</a>
  </li>
   <li>
   <a href="https://twitter.com" rel="nofollow" target="_blank" title="{{channel.channel_name}} On Twitter"><i aria-hidden="true" class="fa fa-twitter fa-2x" style='color:#ee6f00'></i> Twitter</a>
   </li>
</ul>

@LGSon走

在正确的轨道上,但他的回答只隐藏了超链接,而不是它的li父链接。

这将解决问题:

// Get all the hyperlinks that don't have anything after "https://" into an array and loop the array
Array.prototype.slice.call(document.querySelectorAll("a[href='https://']")).forEach(function(link){
  link.parentElement.classList.add("hidden");
});
.hidden { display:none; } /* Add this class to any element that should be hidden */
<ul class="list-inline">
  <li><a href="https://something">Link 1</a></li>
  <li><a href="https://">Link 2</a></li>
</ul>

笔记:

  • .forEach()并非在所有节点列表中普遍受支持当前浏览器,因此转换返回的节点列表 需要.querySelectorAll()才能确保跨浏览器支持。
  • 通常最好使用 CSS 类,而不是添加/删除内联样式。这促进了更多的可重用性和更少的代码冗余。使用 element.classList 属性以便于访问。

最新更新