jQuery 通过 ID 进行过滤,然后捕获匹配项
-
21-08-2019 - |
题
我发现自己重复这样做。
$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() {
});
将选择具有 ID 的所有按钮 以。。开始 用户和 以。。结束 编辑。
尽管老实说,看看您的用例,最好简单地为所有用于编辑用户的按钮提供“edit_user”类,然后执行以下操作:
$jq('button.edit_user').click(function() {
});
它更干净、更快,并且是获取具有类似目的的所有元素的 jQuery 方式。
就获取用户 ID 而言,该网站上对自定义属性进行了一些热烈的讨论(自定义属性 - 是还是不是?)我个人也这样做 data-userid='5'
在我的元素中,然后就做 var id = $(this).attr('data-userid');
获取身份证。好,易于。但不会验证为 XHTML。
其他提示
您可以存储元件本身上的ID(使用jQuery的数据方法)当你这样做的过滤器,然后检索在单击处理该值。
$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);
});
这不是你想要的完美的解决方案,但它是一种方式......
不隶属于 StackOverflow