我已经忙了一段时间了。基本上,我需要检查类名为.pdf-download
的锚点标签上的href
是否为空,如果是,则隐藏它。
我已经尝试了几个选项,但都没有成功。以下是我的代码:
$("a.pdf-download").each(function (i) {
if ($('[href]:empty',this).length == 1) {
$(this).hide();
} else {
$(this).show();
}
});
我已经忙了一段时间了。基本上,我需要检查类名为.pdf-download
的锚点标签上的href
是否为空,如果是,则隐藏它。
我已经尝试了几个选项,但都没有成功。以下是我的代码:
$("a.pdf-download").each(function (i) {
if ($('[href]:empty',this).length == 1) {
$(this).hide();
} else {
$(this).show();
}
});
if ($(this).attr('href') != '') {
$(this).hide();
} else {
$(this).show();
}
请注意,您还可以使用属性选择器在CSS中实现此操作:
a.pdf-download[href='']{
display:none;
}
不过,这在ie6中不被支持。
$('a[href=""]').hide();
- mrtsherman// Hide any links with blank href or no href attribute
$('a.pdf-download[href=], a.pdf-download:not([href])').hide();
使用此解决方案,即使未定义 href
属性,也能生成所需的结果。如果使用 CSS 选择器(jQuery),则无法检测不存在的 href
属性。
$("a.pdf-download").each(function (i) {
if (!this.href) {
$(this).hide();
} else {
$(this).show();
}
})
不必使用JQuery方法来获取href
属性,因为this.href
同样易于阅读、更快,并且具有普遍支持。
$("a.pdf-download").each(function (i) {
if ($(this).attr('href').length == 0) {
$(this).hide();
} else {
$(this).show();
}
});
$('<a>test</a>').attr('href').length
,它将返回 "TypeError: Cannot read property 'length' of undefined",因为 .attr('href')
返回 undefined
。我想在大多数情况下这种方法都可以正常工作,但值得注意的是这个细节。 - andyface我自己也是一个jQuery的初学者,但这是我会做的:
$("a.pdf-download").each(function (i) {
var aHref = $(this).attr('href');
if (aHref == '' || !aHref) {
$(this).hide();
};
});
$(function() {
$('a').each(function() {
(!$(this).attr('href')) ? $(this).hide() : $(this).show();
});
});
$("a.pdf-download").each(function() {
var href = $(this).attr("href");
if(href == '') {
$(this).remove();
}
});
或
$("a.pdf-download[href='']").remove()