根据复选框值regex切换div

时间:2017-09-21 07:46:14

标签: jquery regex

我正在尝试根据regex

的复选框值来切换div

我将唯一ID设为data-row-id并使用该值我试图隐藏并显示div

这是我的正则表达式

new RegExp("^" + $("input[type='checkbox'].filter-industry:checked").map(function () { 
  return $(this).data("rowId"); 
}).get().join("|") + "$");

然后我这样做

$("div.industry-ri-box").each(function () { 
  var $this = $(this); 
  $this[rowIds.source !== "0" 
    && rowIds.test($this.data("rowId")) ? "fadeIn" : "fadeOut"](); });

似乎工作完美,但对于某种组合,它搞砸了。我知道正则表达式有问题但无法弄明白

我通过遵循stackoverflow回答得到了这一点,遗憾的是我无法找到它以供参考。

这是

sample codepen

3 个答案:

答案 0 :(得分:2)

会计打破了正则表达式,因为它的id是1.因此如果1在id中的任何位置,例如18,它将被显示。

将var rowIds行更改为此行,因此每个数字都会被行开头/结尾字符(^和$)包围:

var rowIds = new RegExp("^" + $("input[type='checkbox'].filter-industry:checked").map(function () { return $(this).data("rowId"); }).get().join("$|^") + "$");

答案 1 :(得分:1)

尝试在你的正则表达式的内容周围添加大括号,所以最终不是它:^5|1|18$它应该是^(5|1|18)$

以下是相关行:

new RegExp("^(" + $("input[type='checkbox'].filter-industry:checked").map(function () { 
    return $(this).data("rowId"); 
}).get().join("|") + ")$");

答案 2 :(得分:0)

我不会将regex用于您的特定用例。

这样的事情 - 将框的显示和隐藏与复选框行为分开 - 感觉更好:

$(function() {
  var $industryCheckboxes = $("input[type='checkbox'].filter-industry");
  function updateBoxVisibility() {
    var checkedIds = $industryCheckboxes.filter(":checked")
            .map(function() {
              return $(this).data("rowId");
            })
            .get();
    $("div.industry-ri-box").each(function() {
      var $box = $(this);
      var shouldShow = (checkedIds.includes(0) || checkedIds.includes($box.data("rowId")));
      $box[shouldShow ? 'fadeIn' : 'fadeOut']();
    });
  }
  $industryCheckboxes.on("change", function(e) {
    var $checkbox = $(this);
    if(this.checked) {
      if($checkbox.data("rowId") == "0") {
        $industryCheckboxes.slice(1).prop("checked", false);
      } else {
        $industryCheckboxes.first().prop("checked", false);
      }
    }
    updateBoxVisibility();
  });
});
相关问题