12

我有一些使用 PHP 创建的 div。div 中的锚点总是有一个 HREF,即使它是空白的。基本上,我试图检测 HREF 是否为空白。如果它有内容,什么也不做,如果它是空白的,去掉文本,删除锚点,他们把文本放回去。

这是div:

<div class="title"> 
    <a class="article" href="">Lorem Ipsum</a> 
</div> 

这是我的代码:

jQuery(document).ready(function($) { //required for $ to work in Wordpress

    $(".article").each(function(){
        if ($(this).attr('href') !== undefined) {
            return;
        } else {
            var linkTitle = $(this).html();
            $(this).parent().empty().html(linkTitle);
        }                               
    });    
//-->
});
4

3 回答 3

18

您可以简单地将属性测试为布尔值,而不是针对undefined

if ($(this).attr('href')) {
  // href is not blank
} else {
  // href is blank
}
于 2010-09-22T20:13:46.383 回答
16

您可以使用以下方式检查空href属性并“解包”这些链接.replaceWith()

$(".article[href='']").replaceWith(function() { return this.innerHTML; });

你可以在这里试一试

于 2010-09-22T20:13:04.760 回答
1

要简单地摆脱“href”属性:

$("#myLink[href='']").removeAttr('href');

对于多个定位,例如“样式”属性:

$("#myDiv td, a, p, table, nav, header[style='']").removeAttr('style');

这样,您只会在 Attribute 为空时摆脱它,而不是删除整个元素本身。

一个完整的代码示例是:

$('#myDiv table, tr, td, a, p').each(function() { 
if ($(this).attr('style') == '') { 
    $(this).removeAttr('style'); 
} 
})
于 2012-06-24T17:09:31.670 回答