【问题标题】:Get Id of Row that Matches Regex with data attribute获取将正则表达式与数据属性匹配的行 ID
【发布时间】:2019-04-09 00:19:22
【问题描述】:

我有一个函数:

  1. 过滤 tr 行
  2. 根据传递给函数的值创建一个批准的正则表达式
  3. 创建一个 rtnData 数组,其中包含我认为具有与批准的正则表达式匹配的数据属性的行。

我想要的只是匹配行的 id,而不是 rtnData 正在做什么。

function filterPay(val){
        // target Rows
            $(".loading tr").hide().filter(function() {

        var rtnData = "";
        //make approved regex based on given value
        var payApproved=    new RegExp(val.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), 'i');

           //make rtnData array? consisting of rows that match regex
            rtnData = (
                        $(this).attr("data-payment").match(payApproved)
            );

        return rtnData;

        }).fadeIn("fast");
    }

//I know this refers to the unique Id of each row but don't know how to 
// chain it with the match selection
console.log($(this).attr('data-row'));

因此,不是显示行,而是可以只获取 id 并将它们推入一个新数组,因为在此之后我必须将该数组与另一个过滤器数组匹配,并且只显示两个数组匹配的行身份证。

【问题讨论】:

    标签: javascript jquery regex filter custom-data-attribute


    【解决方案1】:

    您的代码将tr 列表过滤到data-payment 与正则表达式匹配的那些。您现在只需对结果执行map 并提取 id。

    您也不应该在filter 中创建正则表达式,因为它不受每个tr 的影响

    function filterPay(val) {
      var payApproved = new RegExp(val.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), 'i');
    
      // target Rows
      var rows = $(".loading tr").hide().filter(function() {
          // only use test if the reguar expression does not have the global flag set
          return payApproved.test($(this).attr("data-payment"));
      }).fadeIn("fast");
      var ids = rows.get().map(function(row){return row.id});
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2011-09-03
      • 1970-01-01
      • 2011-04-12
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多