:包含多个单词 [英] :contains for multiple words

查看:89
本文介绍了:包含多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下jQuery

I am using the following jQuery

var etag = 'kate'
if (etag.length > 0) {
    $('div').each(function () {
        $(this).find('ul:not(:contains(' + etag + '))').hide();
        $(this).find('ul:contains(' + etag + ')').show();
    });
}​

指向以下HTML

<div id="2">
<ul>
  <li>john</li>
  <li>jack</li>
</ul>
<ul>
  <li>kate</li>
  <li>clair</li>
</ul>
<ul>
  <li>hugo</li>
  <li>desmond</li>
</ul>  
<ul>
  <li>said</li>
  <li>jacob</li>
</ul>
  </div>

    <div id="3">
<ul>
  <li>jacob</li>
  <li>me</li>
</ul>
<ul>
  <li>desmond</li>
  <li>george</li>
</ul>
<ul>
  <li>allen</li>
  <li>kate</li>
</ul>  
<ul>
  <li>salkldf</li>
  <li>3kl44</li>
</ul>
</div>

基本上,只要etag有一个单词,代码就可以完美运行并隐藏那些不包含etag的元素.我的问题是,当etag是多个单词(并且我无法控制它时.它来自数据库,并且可能是多个单词的组合,并用空格字符分隔),然后代码不起作用.

basically, as long as etag has one word, the code works perfectly and hides those elements who do not contain etag. My problem is, when etag is multiple words (and I don't have control over it. Its coming from a database and could be combination of multiple words separated with space char) then the code does not work..

有什么办法可以做到这一点?

is there any way to achieve this?

推荐答案

此过滤器检查给定字符串中的任何单词是否与元素的文本匹配.

This filter checks if any of the words in the given string match the text of the element.

jQuery.expr[':'].containsAny = function(element, index, match) {
    var words = match[3].split(/\s+/);
    var text = $(element).text();
    var results = $.map(words, function(word) {
        return text === word;
    });
    return $.inArray(true, results) !== -1;
};

显示和隐藏为:

$('ul').hide();
$('li:containsAny(john kate)').parents('ul').show();

此处中查看示例.

这篇关于:包含多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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