jQuery文本属性选择器 [英] jQuery text attribute selector

查看:111
本文介绍了jQuery文本属性选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用text属性作为选择器,但是我不太了解这种行为,如果有人可以解释的话,我将不胜感激.例如,给定<span class="span_class"><a class="a_class">text</a></span>$('a.a_class').text()给出预期的文本".但是$('a.a_class[text]')将不匹配任何元素,$('span.span_class > a.a_class[text]')也将不匹配,但是$('span.span_class* > a.a_class[text]')都将匹配(尽管在IE中不是). 对于IE,我能想到的唯一解决方法是:循环访问跨度中包含的所有锚点,在每个锚点上使用.text()并将其与特定条件进行匹配,但这似乎比使用内置选择器慢.任何人都有更好的主意吗?

I am trying to use the text attribute as a selector, but I can't quite grasp the behaviour, would really appreciate if someone could explain. For example given <span class="span_class"><a class="a_class">text</a></span>, $('a.a_class').text() gives "text" as expected. However $('a.a_class[text]') wouldn't match any elements, and neither would $('span.span_class > a.a_class[text]'), but $('span.span_class* > a.a_class[text]') would (although not in IE). The only workaround I can think of for IE, is loop through all anchors contained in a span, use .text() on each and match it against a certain criteria, but it seems slower than using in-built selectors. Anyone have better ideas?

推荐答案

使用自定义选择器的原因

what about using a custom selector

$(document).ready(function(){
  $.extend($.expr[':'], {
    notext: function(elem, i, attr){
      return( $(elem).text() === "" );
    }
  });        
});

简介

$('span:notext').remove();

您甚至可能想要创建一个处理正则表达式的选择器,例如

you might even want to create a selector that handles Regular Expressions like

$.extend($.expr[':'], {
   'content': function(elem, i, attr){      
     return( RegExp(attr[3]).test($(elem).text()) );
   }
});

简介

$('span:content(^api_)').remove();

将选择并删除所有以api_

这篇关于jQuery文本属性选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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