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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3773195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:04:32  来源:igfitidea点击:

How do I check for empty attr() in jquery?

jqueryeachattr

提问by Jared

I have a few divs that are created using PHP. The anchor within the div always has a HREF, even if it is blank. Basically, I am trying to detect if the HREF is blank. If it has content, do nothing, if it's blank, strip the text out, delete the anchor, them put the text back in.

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

Here is the div:

这是div:

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

Here is my code:

这是我的代码:

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

回答by Nick Craver

You can check for an empty hrefattribute and "unwrap" those links using .replaceWith()like this:

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

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

You can give it a try here.

你可以在这里试一试

回答by meagar

You can simply test the attribute as a boolean instead of testing it against undefined:

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

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

回答by Kevin

To simply get rid of the 'href' attribute:

简单地去掉 'href' 属性:

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

For multiple targeting, for example the 'style' attribute:

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

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

This way, you'll only get rid of the Attribute when it's empty instead of deleting the whole element itself.

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

A full code example would be:

完整的代码示例是:

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