jQuery通过ID进行筛选,然后捕获匹配项
我发现自己在重复这样做jQuery通过ID进行筛选,然后捕获匹配项,jquery,css-selectors,pattern-matching,Jquery,Css Selectors,Pattern Matching,我发现自己在重复这样做 $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 ' + use
$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);
});
谢谢。您可以在执行筛选时将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);
});
避免第一场比赛怎么样
$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')代码>以获取ID。非常简单。但不会验证为XHTML。我个人会预处理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);
});
这不是一个完美的解决方案,但它是一种方式…我同意使用“编辑用户”类,但我需要一个指向每个按钮的用户id链接。我可以这样做,但我需要做匹配来获得用户ID。+1该死的Paolo…你把我带进了那天的最后十张选票中,其中2张或3张是你的。停止提供洞察力!如果你愿意的话,你可以取消投票,我在两小时前就达到了我的每日上限。我就是停不下来PNO并不是这个解决方案的忠实粉丝,因为它仍然需要对所有按钮进行一系列不必要的扫描。如果存在匹配项,至少您可以在each上添加一个类,将其与click链接在一起,并完全避免使用filter函数。所以:$('button')。每个(…)。过滤器('.user_edit')。单击(…);没错,但我是在当前问题的背景下提出了一个解决方案(不改变标记)