如何检查jquery中的空attr()?

我有一些使用PHP创建的div。 div中的锚点总是有一个HREF,即使它是空白的。 基本上,我试图检测HREF是否为空白。 如果它有内容,则不执行任何操作,如果它是空白的,则删除文本,删除锚点,然后将文本放回原位。

这是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); } }); //--> }); 

你可以检查一个空的href属性,并使用.replaceWith()像这样“解开”这些链接:

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

你可以在这里尝试一下 。

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

 if ($(this).attr('href')) { // href is not blank } else { // href is blank } 

要简单地摆脱’href’属性:

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

对于多个定位,例如’style’属性:

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

这样,只有在空的时候才会删除属性,而不是删除整个元素本身。

完整的代码示例如下:

 $('#myDiv table, tr, td, a, p').each(function() { if ($(this).attr('style') == '') { $(this).removeAttr('style'); } })