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

时间:2018-04-16 18:35:06

标签: javascript html css

我使用以下内容显示用户的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帐户。如果li之后的href值为空,有没有办法隐藏https://。换句话说,如果我的{{channel.facebook_page}}为空白隐藏th li

4 个答案:

答案 0 :(得分:2)

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

使用CSS属性选择器[attribute='value'],并执行类似的操作。

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

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

答案 1 :(得分:1)

我不知道您使用什么框架进行模板化,我会根据您的个人资料中的标记对其进行猜测并猜测Angular。

你可以使用Angular与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>

答案 2 :(得分:0)

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

&#13;
&#13;
document.querySelectorAll('[href="https://"]').forEach(function(el) {
    el.parentElement.style.display = 'none';
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

@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 属性可以轻松访问。