JQuery filter through identifiers and then capture matches

I find myself doing it multiple times.

$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);
});

So I want to apply the click event to some buttons, and in the click event handler I need a user ID. Is there a way to avoid the second match?

$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);
});

Thanks.

+3
source share
3 answers

How to avoid the first match?

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

});

Select all buttons with an identifier that starts with the user and ends with editing.

, , , "edit_user", :

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

});

, jQuery , .

, ( - Yay nay?), data-userid='5' , var id = $(this).attr('data-userid');, . . XHTML.

+10

( 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

Personally, I would like to handle the DOM:

$(function() {

$("button").each(function() { 
      var matches = $(this).attr("id").match(/^user_(\d+)_edit$/);

      if (matches) {
         $(this).data("user_edit_id",matches[1]);
      }
   }
});

Then you can simply:

$("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);
});

This is not an ideal solution for what you want, but it is one way ...

0
source

Source: https://habr.com/ru/post/1711507/


All Articles