jQuery :contains selector to search for multiple strings

后端 未结 4 1670
刺人心
刺人心 2020-11-27 12:26

Assuming i have:

  • Mary
  • John, Mary, Dave
  • John, Dave, Mary
  • 4条回答
    •  难免孤独
      2020-11-27 13:07

      Answer

      The correct syntax would be $("li:contains('John'),li:contains('Mary')").css("color","red")

      But I found out that if you had many cases to test, jQuery will perform very badly (especially on IE6, I know, it's old but still in use). So I decided to write my own attribute filter.

      This is how to use it: $("li:mcontains('John','Mary')").css("color","red")

      Code

      jQuery.expr[':'].mcontains = function(obj, index, meta, stack){
          result = false;     
          theList = meta[3].split("','");
      
          var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
      
          for (x=0;x= 0) {
                  return true;
              }
          }
      
          return false;
      };
      

    提交回复
    热议问题