jquery 获取所有匹配数据属性名称的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20092558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery get all elements matching data attribute name
提问by Marty Wallace
say i have a few elements with the following data attribute:
说我有几个具有以下数据属性的元素:
<data-my-key="blah">
and i want to attach an event to them all, how can this be done?
我想为他们所有人附加一个事件,这怎么做?
I have tried a few things but cant get it to work.
我已经尝试了一些东西,但不能让它工作。
My latest attempt was:
我最近的尝试是:
$('data-my-key').click(...
and
和
$(document).find('data-my-key').click(...
回答by Rory McCrossan
You can use the attribute selector:
您可以使用属性选择器:
$('[data-my-key]').click(...
Note however, that jQuery stores data
attributes added after DOM load in it's internal cache not as an attribute on the element, so that selector would not work for those. In that case you would need to use filter
:
但是请注意,jQuery 将data
DOM 加载后添加的属性存储在其内部缓存中,而不是作为元素上的属性,因此选择器不适用于那些。在这种情况下,您需要使用filter
:
$(document).children().filter(function() {
return $(this).data('my-key');
}).click(...;
回答by Adil
You can use has attribute selectorand give the attribute name.
您可以使用has 属性选择器并给出属性名称。
$('[data-my-key]').click...