admin管理员组文章数量:1332336
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 badges4 Answers
Reset to default 4Use 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
版权声明:本文标题:javascript - How do I use .filter to return multiple values? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742262884a2442844.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论