如何在jQuery中选择与this属性匹配的所有元素
how to select all elements with matching attribute of this in jQuery?
我想使用this
选择器选择div中与所选元素具有相同属性的所有元素。
因此,在我的示例中,当我单击类为.foo
的元素时,我希望在.container
中查找与单击的元素共享相同data-index
属性的所有元素,然后添加.bah
类。目前,我的函数只将.bah
添加到被点击的元素中,我了解如何选择某些属性,但不了解与this
选择器有关的属性。
Javascript:
$(document).on('click','.foo', function() {
$(this).addClass('bah');
});
HTML:
<div class="container">
<div class="inner1">
<div data-index="0" class="foo">
<p>item 1</p>
</div>
<div data-index="2" class="foo">
<p>item 2</p>
</div>
</div>
<div class="inner2">
<div data-index="0" class="foo">
<p>item 1</p>
</div>
<div data-index="2" class="foo">
<p>item 2</p>
</div>
</div>
</div>
您可以使用.filter()
来获得结果。
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$('.container div').filter(function(){
return $(this).data('index') === dataIndex
}).addClass('bah');
});
或者使用基于属性的选择器。
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$('.container div[data-index="'+dataIndex+'"]').addClass('bah');
});
$(document).on('click','.foo', function() {
var dataIndex = $(this).data('index');
$(document).find("div[data-index='" + dataIndex + "']").each(function() {
$(this).addClass('bah');
});
});
Fiddle示例:http://jsfiddle.net/9huw0ym9/1/
相关文章:
- javascript来显示元素属性
- 自定义HTML元素属性未显示-Web组件
- 主元素属性?(或技术)
- 使用模板后,使用Angular获取元素属性值
- 如何从不同范围外的元素属性中获取求值表达式
- 可以't访问元素属性(如果已明确设置)
- 传递引用 jQuery 后无法访问元素属性
- 如何替换元素属性中的部分文本
- 添加新元素属性
- 如何使用jQuery访问父元素属性
- 使用jQuery.attr()方法获取元素属性
- 修改时,哪些DOM元素属性会导致浏览器执行回流操作
- Javascript数据将元素属性绑定到URL中的锚href
- 初始化可从元素属性值观察到的Knockout
- 获取内联样式中的元素属性
- 如何在 html 元素属性中使用 Angular 2 外推法
- 将元素属性与 javascript 折叠方法结合使用时,引导折叠无法正常工作
- 如何观察聚合物元素属性值从索引.html的变化
- 使用 JavaScript 修改 DOM 元素属性
- 聚合物节点到元素属性