如何在 jquery 中检查空 attr()? [英] How do I check for empty attr() in jquery?

查看:37
本文介绍了如何在 jquery 中检查空 attr()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这里是div:

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

这是我的代码:

jQuery(document).ready(function($) {//需要 $ 在 Wordpress 中工作$(".article").each(function(){if ($(this).attr('href') !== undefined) {返回;} 别的 {var linkTitle = $(this).html();$(this).parent().empty().html(linkTitle);}});//-->});

解决方案

您可以检查空的 href 属性并使用 .replaceWith() 像这样:

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

你可以在这里试一试.

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.

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

解决方案

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

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

You can give it a try here.

这篇关于如何在 jquery 中检查空 attr()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆