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);
});
谢谢。
I find myself doing this 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);
});
So I want to apply a click event to some buttons and in the click event handler I need the user ID. Is there a way I can avoid the second match?
$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);
});
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
避免第一场比赛怎么样?
将选择 ID 为 以 用户和 以编辑结尾。
尽管老实说,看看您的用例,最好简单地为所有用于编辑用户的按钮提供“edit_user”类,然后执行以下操作:
它更干净,更快,并且是获取所有内容的 jQuery 方式具有类似目的的元素。
就获取用户 ID 而言,该网站上对自定义属性进行了一些热烈的讨论(自定义属性 -是还是不?),我个人在我的元素中执行
data-userid='5'
,然后执行var id = $(this).attr('data- userid');
获取 ID。 好,易于。 但不会验证为 XHTML。How about avoiding the first match?
Would select all buttons that have an ID that starts with user and ends with edit.
Although honestly, looking at your use case, it would be WAY better to simply give all buttons that are meant to edit a user a class of "edit_user" and then just do:
It is cleaner, faster, and the jQuery way of getting all elements that serve a similar purpose.
As far as getting the user id there's been some lively discussion on custom attributes on this site (Custom attributes - Yay or nay?) and I personally do
data-userid='5'
in my elements and then just dovar id = $(this).attr('data-userid');
to get the ID. Nice and easy. Won't validate as XHTML, though.您可以将 ID 存储在元素本身上(使用 jQuery 的 data 方法)过滤器,然后在单击处理程序中检索该值。
You could store the ID on the element itself (using jQuery's data method) when you do the filter, and then retrieve that value in the click handler.
就我个人而言,我会预处理 DOM:
然后你可以简单地:
这不是你想要的完美解决方案,但它是一种方法......
Personally, I would preprocess the DOM:
Then you can simply:
It's not a perfect solution to what you want, but it's one way...