Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - If text matches string and if text does not match string

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');
}   
})
});

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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');
  }   
 })
});

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...