如果文本与字符串匹配,并且文本与字符串不匹配 [英] If text matches string and if text does not match string

查看:106
本文介绍了如果文本与字符串匹配,并且文本与字符串不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表中有一些文本",如果匹配,那么我将在.input-1下拉列表中显示选择选项,但是我无法使用的是与字符串不匹配的相反.在这种情况下,我想隐藏选择选项.

I have 'some text' in a list and if this matches then I am showing select options in .input-1 dropdown, but what I cannot get to work is the opposite where it does not match the string. In this case, I want to hide the select options.

代码的第一部分有效,但是如果失败,则第二部分

The first part of the code works, but second else if fails

jQuery(document).ready( function() {
$('.input-1 option').each(function() {
var ourOption = $(this).text().toLowerCase(); // convert text to Lowercase
var str = "Some Text";
var res = str.toLowerCase();
if (ourOption.match(res)) {
$(this).css('display', 'block');
}
else if (!ourOption.match(res)) {
$(this).css('display', 'none');
}   
})
});

当前结果是,无论匹配的文本如何,所有选项都被隐藏,因此我猜测else出现错误(如果没有匹配项的语法不正确).

The current result is that all options are hidden regardless of the matched text so I'm guessing there is an error in my else if or the syntax for no match is incorrect.

推荐答案

.match()是在字符串中查找匹配项,而不是比较并返回true/false.您需要在这里比较==

.match() is to find a match in string, not compare and return true/false. You need comparison == here:

jQuery(document).ready( function() {
 $('.input-1 option').each(function() {
  var ourOption = $(this).text().toLowerCase(); // convert text to Lowercase
  var str = "Some Text";
  var res = str.toLowerCase();
  if (ourOption.indexOf(res) > -1) {
    $(this).css('display', 'block');
  }
  else {
    $(this).css('display', 'none');
  }   
 })
});

事实上,您甚至不需要一个else-如果在这里,仅此而已就足够了...因为只有两种可能,true和false都用if/else覆盖.

As a matter of fact you do not even need an else-if here, just else is enough... because there are only 2 possibilities true and false and both are covered with if/else.

这篇关于如果文本与字符串匹配,并且文本与字符串不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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