Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

How do I make jQuery Contains case insensitive, including jQuery 1.8+?

I'm trying to use "contains" case insensitively. I tried using the solution at the following stackoverflow question, but it didn't work:

Is there a case insensitive jQuery :contains selector?

For convenience, the solution is copied here:

jQuery.extend(
        jQuery.expr[':'], { 
                Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0" 
});

Here is the error:

Error: q is not a function
Source File: /js/jquery-1.4.js?ver=1.4
Line: 81

Here's where I'm using it:

  $('input.preset').keyup(function() {
    $(this).next().find("li").removeClass("bold");
    var theMatch = $(this).val();
    if (theMatch.length > 1){
      theMatch = "li:Contains('" + theMatch + "')";
      $(this).next().find(theMatch).addClass("bold");
    }
  });

My use of the original case sensitive "contains" in the same scenario works without any errors. Does anyone have any ideas? I'd appreciate it.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is what i'm using in a current project, haven't had any problems. See if you have better luck with this format:

jQuery.expr[':'].Contains = function(a, i, m) { 
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
};

In jQuery 1.8 the API for this changed, the jQuery 1.8+ version of this would be:

jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

You can test it out here. For more detail on 1.8+ custom selectors, check out the Sizzle wiki here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...