質問

私自身は、このrepeatedyをやって見つけます。

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

だから私は、をいくつかのボタンにのイベントをクリックして、クリックイベントハンドラで、私は、ユーザー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);
});

感謝します。

役に立ちましたか?

解決

どのように最初の試合を避けてはどうですか?

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

});

のユーザーと の編集を終了します。

正直が、あなたのユースケースを見て、単にユーザーに「EDIT_USER」のクラスを編集してからちょうど行うことを意味しているすべてのボタンを与えることWAY方が良いでしょう。

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

});

これは、クリーナーより速く、そして同様の目的を果たすすべての要素を取得するjQueryの方法です。

限り、ユーザIDの取得など(このサイト上のカスタム属性にいくつかの活発な議論がなされていますカスタム属性 - イェーイかいやの)と私は個人的に私の要素でdata-userid='5'を行い、その後、単にIDを取得するためにvar id = $(this).attr('data-userid');していますか?。ニースと簡単。しかし、XHTMLとして検証しません。

他のヒント

あなたは(jQueryのデータの方法を使用して)要素自体にIDを保存することができあなたはフィルタを行うときに、次にクリックハンドラでその値を取得します。

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

個人的には、前処理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);
});

それはあなたが望むものに完璧なソリューションではないが、それは一つの方法です...

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top