我有一个页面,为简单起见,包含:
<div id="parent">
<div class="commonClass" data-attribute-one="some value" data-attribute-two="some value">
.... (lots more rows)
</div>
在页面顶部,我有两个输入供用户搜索/过滤结果:
下一个挑战是我想要合并两个搜索/过滤器,例如查找具有data-attribute-one值为“A”的所有行以及具有data-attribute-two的所有行包含(* =)'AAAA'。我对以下内容感到满意:
$(".commonClass[data-attribute-one='" + searchValue1 +"']"[data-attribute-two*='" + searchValue2 +"']")
我遇到的困难是如何处理用户将搜索字段归零或从下拉列表中选择“all”(过滤data-attribute-one)的情况?有没有办法更改我现有的选择器以更好地处理空('')searchValue1和/或searchValue2?或者,是动态构造选择器的解决方案,例如
selector = ".commonClass"
if ( searchValue1 != '' ) {
selector += "[data-attribute-one='" + searchValue1 +"']"
} ... etc
答案 0 :(得分:0)
根据Joe Enos和Jaw.sh的评论,我写了一个构造选择器的方法:
function constructSearchSelector() {
var selector = ".commonClasss";
if ( searchValue1 != '' ) {
selector += "[data-attribute-one='" + searchValue1 + "']";
}
if ( searchValue2 != '' ) {
selector += "[data-attribute-two*='" + searchValue2 + "']";
}
return selector;
}
通过这种方式,我可以轻松添加更多搜索条件,并且可以轻松调试构造的值。感谢您的评论!