admin管理员组文章数量:1330565
I apologize if this is a duplicate question. It's such a use-case question that it seems everyone has their own version.
I'm wondering if this can be simplified:
if ($('.taxclass').text().indexOf(tax1)>-1 || $('.taxclass').text().indexOf(tax2)>-1) {}
I apologize if this is a duplicate question. It's such a use-case question that it seems everyone has their own version.
I'm wondering if this can be simplified:
if ($('.taxclass').text().indexOf(tax1)>-1 || $('.taxclass').text().indexOf(tax2)>-1) {}
Share
asked Feb 26, 2013 at 16:30
Adam CookAdam Cook
6202 gold badges7 silver badges21 bronze badges
4
- 1 absolutly, use pure js instead of jquery, thats a 40-70kb reduce :) – Toping Commented Feb 26, 2013 at 16:33
- 1 @Ark doesn't really matter if OP has other jQuery dependencies, which is most likely the case if he is posting jQuery code. – Fabrício Matté Commented Feb 26, 2013 at 16:34
- I can't get over how quickly the answers e on this site. :) – Adam Cook Commented Feb 26, 2013 at 16:37
- @FabrícioMatté you're doing a assumption of my assumption, that's a inception :) – Toping Commented Feb 26, 2013 at 16:39
6 Answers
Reset to default 4It's pretty simple as it stands, but you could make it a bit less redundant mainly by getting the elements text only once and reusing the variable:
var text = $('.taxclass').text();
if (text.indexOf(tax1)>-1 || text.indexOf(tax2)>-1) {
}
A further note could be to reduce the traversal of the DOM by using an identifier and looking only for a distinct element (if that suits your needs) instead of every possible thing that has the class taxclass
.
var txt = $('.taxclass').text();
if (txt.indexOf(tax1)>-1 || txt.indexOf(tax2)>-1) {}
One super quick way would be not to duplicate $('.taxclass').text()
Try something like
var tax = $('.taxclass').text();
if (tax.indexOf(tax1)>-1 || tax.indexOf(tax2)>-1) {}
You can store $('.taxclass').text()
in a variable, or use regex.
var str = $('.taxclass').text();
if (str.indexOf(tax1) > -1 || str.indexOf(tax2) > -1)
// Or with regex
if(/(text1)|(text2)/.test($('.taxclass').text())
{}
Quick and dirty:
text.indexOf(tax1+"~"+tax2)>-1
Functional, works on n strings, but verbose:
[tax1, tax2].some(function(s) { return s.indexOf(text)>-1 })
As a prototype:
String.prototype.foundIn = function() {
var s=this; return Array.prototype.slice.call(arguments).some(function(m)
{return m.indexOf(s)>-1});
};
Usage:
$('.taxclass').text().foundIn(tax1, tax2)
What about:
f = function (x) { return $('.taxclass').text().indexOf(x) > -1; }
if (f(tax1) || f(tax2)) {}
本文标签: simplify javascript if statement where conditions are identical except for variableStack Overflow
版权声明:本文标题:simplify javascript if statement where conditions are identical except for variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742221372a2435463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论