我发现自己重复这样做。
$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);
});
谢谢。
最佳答案
避免第一场比赛怎么样?
$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。
关于jQuery 通过 ID 进行过滤,然后捕获匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1059595/