如何用jquery或javascript隐藏空的href值按钮

问题描述 投票:0回答:2

当我尝试隐藏href属性中没有任何值的按钮时,jquery代码出现问题,如何正确修复它?我的代码:

<a id="tw" href=""> Twitter</a>
<a id="fb" href="http://m.facebook.com"> Facebook</a>

<script>
$('#tw').each(function() {
    if($('#tw').attr('href') === '') {
        $(this).parents('#tw').hide();
    }
});
</script>
javascript jquery html dom
2个回答
1
投票

[您需要选择所有链接a并检查href属性,您只选择了一个(#tw]

$('a').each(function() {
  if (!$(this).attr('href')) {
    $(this).hide();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="tw" href=""> Twitter</a>
<a id="fb" href="http://m.facebook.com"> Facebook</a>

更好的是,使用css选择器获取具有空href的链接并将其隐藏起来:

$('a[href=""]').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="tw" href=""> Twitter</a>
<a id="fb" href="http://m.facebook.com"> Facebook</a>
<a id="other" href=""> Another link</a>

或只是CSS:

a[href=""]{
  display: none;
}
<a id="tw" href=""> Twitter</a>
<a id="fb" href="http://m.facebook.com"> Facebook</a>
<a id="other" href=""> Another link</a>

0
投票
$('#tw').each(function() {
    if($(this).attr('href') != '') {
        $(this).parents('#tw').show();
    }
});

0
投票

.hide()添加到$(this)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="tw" href=""> Twitter</a>
<a id="fb" href="http://m.facebook.com"> Facebook</a>

<script>
$('#tw').each(function() {
    if($('#tw').attr('href') === '') {
        console.log("empty href");
        $(this).hide();
    }
});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.