jQuery过滤ID然后捕获匹配

时间:2009-06-29 17:56:37

标签: jquery css-selectors pattern-matching

我发现自己这样做了。

$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事件处理程序中我需要用户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);
});

感谢。

3 个答案:

答案 0 :(得分:10)

避免第一场比赛怎么样?

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

});

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

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

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

});

它更清晰,更快,并且jQuery方式可以获得所有用于类似目的的元素。

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

答案 1 :(得分:3)

您可以在执行过滤器时将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);
});

答案 2 :(得分:0)

就个人而言,我会预处理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);
});

这不是你想要的完美解决方案,但它是单向的......