【问题标题】:jQuery filter through IDs and then capture matchesjQuery 通过 ID 过滤,然后捕获匹配项
【发布时间】:2009-06-30 02:22:53
【问题描述】:

我发现自己反复这样做。

$jq("button").filter(function(){
    return this.id.match(/^user_(\d+)_edit$/);
}).click(function(){
    var matches = this.id.match(/^user_(\d+)_edit$/);
    var user_id = matches[1];

    alert('click on user edit button with ID ' + user_id);
});

所以我想对一些按钮应用 click 事件,并且在 click 事件处理程序中我需要用户 ID。有没有办法避免第二场比赛?

$jq("button").filter(function(){
    return this.id.match(/^user_(\d+)_edit$/);
}).click(function(){
    var user_id = some_magic_variable;

    alert('click on user edit button with ID ' + user_id);
});

谢谢。

【问题讨论】:

    标签: jquery css-selectors pattern-matching


    【解决方案1】:

    避免第一场比赛怎么样?

    $jq("button[id^=user][id$=edit]").click(function() {
    
    });
    

    将选择 ID 为 starts with 用户和 ends with 编辑的所有按钮。

    虽然老实说,看看你的用例,最好简单地给所有用于编辑用户的按钮一个“edit_user”类,然后做:

    $jq('button.edit_user').click(function() {
    
    });
    

    它更简洁、更快,并且是 jQuery 获取所有用于类似目的的元素的方式。

    就获取用户 ID 而言,本网站 (Custom attributes - Yay or nay?) 上对自定义属性进行了一些热烈的讨论,我个人在我的元素中使用 data-userid='5',然后只需使用 var id = $(this).attr('data-userid'); 来获取 ID。好,易于。不过,不会验证为 XHTML。

    【讨论】:

    • 我同意使用“edit_user”类,但我需要一个指向每个按钮的 user_id 链接。我可以这样做 但我仍然需要匹配才能获取用户 ID。
    • +1 该死的 Paolo...为你投票让我进入了我当天的最后十票——其中 2 或 3 票是你的。停止提供见解!
    • 如果您愿意,可以取消投票,我在 2 小时前达到了每日上限。我就是停不下来! :P
    【解决方案2】:

    您可以在执行过滤器时将 ID 存储在元素本身(使用 jQuery 的 data 方法),然后在点击处理程序中检索该值。

    $jq("button").filter(function(){
        var $this = $jq(this);
        var matches = $this.attr('id').match(/^user_(\d+)_edit$/);
    
        if (matches) {
            $this.data('idNumber', matches[1]);
        }
    
        return matches;
    }).click(function(){
        var user_id = $(this).data('idNumber');
    
        alert('click on user edit button with ID ' + user_id);
    });
    

    【讨论】:

      【解决方案3】:

      就我个人而言,我会预处理 DOM:

      $(function() {
      
      $("button").each(function() { 
            var matches = $(this).attr("id").match(/^user_(\d+)_edit$/);
      
            if (matches) {
               $(this).data("user_edit_id",matches[1]);
            }
         }
      });
      

      那么你可以简单地:

      $("button").filter(function(){
          return $(this).data("user_edit_id");
      }).click(function(){
          var user_id = $(this).data("user_edit_id");
      
          alert('click on user edit button with ID ' + user_id);
      });
      

      这不是你想要的完美解决方案,但它是一种方式......

      【讨论】:

      • 不是这个解决方案的忠实拥护者,因为它仍然需要对所有按钮进行不必要的扫描。至少,如果有匹配项,您可以在每个上添加一个类,将其与单击链接在一起,并完全避免使用过滤器功能。所以: $('button').each(...).filter('.user_edit').click(...);
      • 没错,但我是在当前问题的背景下提出解决方案(不更改标记)
      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2017-08-06
      • 2013-06-21
      • 2016-10-11
      • 1970-01-01
      • 2015-09-25
      相关资源
      最近更新 更多