jQuery text attribute selector

喜你入骨 提交于 2020-01-24 20:12:23

问题


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?


回答1:


what about using a custom selector

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

Synopsis

$('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()) );
   }
});

Synopsis

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

would select and remove all spans which text begins with api_




回答2:


This is because 'text' in this case is not an attribute. It is the content of the element.

You're looking for the :contains() selector:

$('a.a_class:contains(text)');

http://api.jquery.com/contains-selector/

Keep in mind that this selector will match any part of the string. contains(foo) will match "foo bar" as well.

If you want an exact match of the entire text string, you could use filter()

$('a.a_class').filter(function() {
    return $(this).text() == "text";
});

EDIT:

To find elements whose content starts with a value, you could use a regular expression inside the filter():

$('a.a_class').filter(function() {
    return $(this).text().indexOf( "tex" ) >= 0;
});

EDIT: Updated to use indexOf() instead of regex as recommended by @Nick.



来源:https://stackoverflow.com/questions/3060847/jquery-text-attribute-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!