2009-06-29 42 views
3

我發現自己做了這個反覆。jQuery通過ID篩選,然後捕獲匹配

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

謝謝。

回答

10

如何避免第一場比賽?

$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。

+1

+1比正則表達式匹配漂亮,並提供有用的建議。 – karim79 2009-06-29 18:18:48

+0

我同意使用'edit_user'類,但我需要每個按鈕的user_id鏈接。我可以這樣做

3

當您執行過濾器時,您可以將ID存儲在元素本身(使用jQuery的data方法),然後在click處理程序中檢索該值。

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

這不是你想要的完美的解決方案,但它是一種方式......