【问题标题】:How can I make this Jquery filter not case sensitive?如何使这个 Jquery 过滤器不区分大小写?
【发布时间】:2015-10-02 12:02:46
【问题描述】:

我正在尝试为 html 列表框创建过滤器。列表框从 mysql 数据库填充并正确加载所有内容。我有一个我输入的文本框,列表过滤器完全基于输入的内容。我真的需要这个不区分大小写。换句话说,如果我输入一个大写字母 A,该函数会返回所有以大写字母 A 开头的条目,我需要它返回所有以 a 开头的条目,无论大小写如何。

这是函数

$('#custsearch').keyup(function () {
var valThis = this.value;
    lenght  = this.value.length;

$('.cust').each(function () {
    var text  = $(this).text(),
        textL = text,
        htmlR = '<b>' + text.substr(0, lenght) + '</b>' + text.substr(lenght);
    (textL.indexOf(valThis) == 0) ? $(this).html(htmlR).show() : $(this).hide();
});

});

【问题讨论】:

  • 您是否尝试先使用 javascript .toLowerCase() 转换为小写?

标签: jquery html


【解决方案1】:

使用 toLowerCase() 将两个值转换为小写,然后比较它们

$('#custsearch').keyup(function() {
  var valThis = this.value,
    length = valThis.length;
  $('.cust').each(function() {
    var $this = $(this),
      text = $this.text(),
      htmlR = '<b>' + text.substr(0, length) + '</b>' + text.substr(lenght);
    (text.toLowerCase().indexOf(valThis.toLowerCase()) == 0) ? $this.html(htmlR).show(): $this.hide();
  });
});

【讨论】:

  • length = this.value.length;length = valThis.length.trim() 更好,您还可以做的另一件事是在each 中缓存this 引用
  • 在那种情况下valThis = this.value.trim(),
  • 非常感谢,一旦我修正了上述错字,这项工作就奏效了。伟大的工作,谢谢。
  • @PranavCBalan 您正在访问 DOM 元素引用中的值,当您可以从局部变量访问它时,无需再次访问它
猜你喜欢
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多