当我尝试隐藏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>
[您需要选择所有链接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>
$('#tw').each(function() {
if($(this).attr('href') != '') {
$(this).parents('#tw').show();
}
});
将.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>