admin管理员组

文章数量:1332713

Say I have a div, with some CSS and javascript:

var someCSS = {
  color: 'red',
};
         

$(".test > .sub").filter(function(index) {
   return $(this).text() == 'hello';
 }).css(someCSS);
.test {
  color: green;
}
<script src=".1.1/jquery.min.js"></script>
<div class='test'>
  <div class='sub'>hello</div>
  <div class='sub'>stackoverflow</div>
</div>

Say I have a div, with some CSS and javascript:

var someCSS = {
  color: 'red',
};
         

$(".test > .sub").filter(function(index) {
   return $(this).text() == 'hello';
 }).css(someCSS);
.test {
  color: green;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
  <div class='sub'>hello</div>
  <div class='sub'>stackoverflow</div>
</div>

The above will color the 'hello' red, but I don't understand how to add more values, eg 'hello' and 'stackoverflow'. I obviously can't do return $(this).text() == 'hello' || 'stackoverflow';, but I just can't figure out what to do!

Any suggestions will be appreciated :)

Share asked Dec 31, 2014 at 15:02 downloaderdownloader 3035 silver badges13 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Use an array of values and then check against it, this way, you can add more values as you want and then you could just use Array.prototype.indexOf.

var arr = ['hello', 'stackoverflow'];

and then

return arr.indexOf($(this).text()) > -1;
$(".test > .sub").filter(function(index) {
   return $(this).text() == 'hello' || $(this).text() === 'stackoverflow';
 }).css(someCSS);

or

var values = [
  'hello',
  'stackoverflow'
]

$(".test > .sub").filter(function(index) {
   return values.indexOf($(this).text()) > -1 
 }).css(someCSS);

Close, you need to pare again:

return $(this).text() == 'hello' || $(this).text() == 'stackoverflow'

My own take on this problem is to use Array.prototype.indexOf():

$(".test > .sub").filter(function(index) {
   return ['hello','stackoverflow'].indexOf($(this).text().trim()) > -1;
 }).addClass('someCSS');

The above approach allows for an array of strings that you wish to find to be used, rather than explicitly paring and evaluating a number of strings within the anonymous function; albeit, in this example, I've constructed that array within the same function for brevity.

$(".test > .sub").filter(function(index) {
  return ['hello','stackoverflow'].indexOf($(this).text().trim()) > -1;
}).addClass('someCSS');
.someCSS {
  color: #f00;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
  <div class='sub'>hello</div>
  <div class='sub'>stackoverflow</div>
</div>

References:

  • JavaScript:
    • Array.prototype.indexOf().
    • String.prototype.trim().

本文标签: javascriptHow do I use filter to return multiple valuesStack Overflow