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

问题描述

我的html看起来像这样

My html looks like this

<input id="txt" value=""></input>

<div class="link-item">jK</div>
<div class="link-item">JFOO</div>

我的js

$('#txt').keyup(function(){

    var txtsearch = $('#txt').val();
    var filt = $("div.link-item:contains('" + txtsearch +"')");

    $("div.link-item").css("display", "none")
        .filter(filt)
        .css("display", "block");

});

我正在寻找在客户端动态过滤内容的方法.当我输入大写字母j时,它仅返回第二个div,而我想获取所有包含j的div,无论是大写还是小写.

I'm looking to filter content dynamically on the client side. When I type a capital j, it only returns the second div whereas I want to get all div that contain j whether upper or lower case.

推荐答案

您可以将.contains过滤器更改为不区分大小写,或创建自己的选择器.

You can change the .contains filter to be case insensitive or create your own selector.

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

这将创建一个新的选择器:icontains(或者您可以将其命名为insensitive-contains,或者任何您喜欢的东西).用法与包含相同:$('div:icontains("Stack")');将匹配:

This creates a new selector: icontains (or you could name it insensitive-contains, or whatever suits your fancy).It's usage would be the same as contains: $('div:icontains("Stack")'); would match:

<div>stack</div>
<div>Stack</div>
<div>StAcKOverflow</div>

或覆盖现有的.contains过滤器:

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

有了这个,

$("div:contains('John')");

将选择所有这三个元素:

would select all three of these elements:

<div>john</div>
<div>John</div>
<div>hey hey JOHN hey hey</div>

这篇关于jQuery:contains()选择器大写和小写问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:43