简体   繁体   English

全选的jQuery选择器

[英]jquery selector with select all

I have a page that for simplicity contains this: 为了简单起见,我有一个页面包含以下内容:

<div id="parent">
    <div class="commonClass" data-attribute-one="some value" data-attribute-two="some value">
    .... (lots more rows)
</div>

At the top of the page I have two inputs for the user to search/filter results: 在页面顶部,我有两个输入供用户搜索/过滤结果:

  1. An html select to filter data-attribute-one to a single selection. 一个html select可以将data-attribute-one筛选为单个选择。
  2. An input box to filter data-attribute-two contains name. 用于过滤数据属性两个的输入框包含名称。

The next challenge is that I wanted to combine the two searches / filters, eg find all rows with an data-attribute-one value of "A" AND all rows with a data-attribute-two containing (*=) 'AAAA'. 下一个挑战是,我想结合两个搜索/过滤器,例如,找到所有数据属性为“ A”的行,并找到所有数据属性为“ AAAA”(* =)的行。 I satisfied that with the following: 我对以下内容感到满意:

$(".commonClass[data-attribute-one='" + searchValue1 +"']"[data-attribute-two*='" + searchValue2 +"']")

What I'm having a hard time with is how to handle the case where the user nulls out a search field or selects "all" from the drop down (to filter data-attribute-one)? 我遇到的麻烦是如何处理用户使搜索字段为空或从下拉列表中选择“全部”的情况(以过滤数据属性一)? Is there any way to change my existing selector to better handle an empty ('') searchValue1 and/or searchValue2? 有什么方法可以更改现有选择器以更好地处理空('')searchValue1和/或searchValue2吗? Or, is the solution to dynamically construct the selector along the lines of, eg 或者,是沿着例如

selector = ".commonClass"
if ( searchValue1 != '' ) {
   selector += "[data-attribute-one='" + searchValue1 +"']"
} ... etc

As per the comments from Joe Enos and Jaw.sh, I wrote a method to construct the selector: 根据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;
}

This way I can easily add on more search criteria and I can easily debug the constructed value. 这样,我可以轻松添加更多搜索条件,并且可以轻松调试构造的值。 Thanks for the comments! 感谢您的评论!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM