Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jQuery中选择所有与此属性匹配的元素?_Javascript_Jquery_Html_Attributes_This - Fatal编程技术网

Javascript 如何在jQuery中选择所有与此属性匹配的元素?

Javascript 如何在jQuery中选择所有与此属性匹配的元素?,javascript,jquery,html,attributes,this,Javascript,Jquery,Html,Attributes,This,我想使用this选择器选择div中与所选元素具有相同属性的所有元素 $(document).on('click','.foo', function() { var dataIndex = $(this).data('index'); $('.container div[data-index="'+dataIndex+'"]').addClass('bah'); }); 因此,在我的示例中,当我单击一个类为.foo的元素时,我希望找到.container中与单击的元素共享相同数

我想使用
this
选择器选择div中与所选元素具有相同属性的所有元素

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div[data-index="'+dataIndex+'"]').addClass('bah');
}); 
因此,在我的示例中,当我单击一个类为
.foo
的元素时,我希望找到
.container
中与单击的元素共享相同
数据索引
属性的所有元素,然后添加
.bah
类。目前,我使用的函数仅将
.bah
添加到单击的元素中,我了解如何选择某些属性,但与
选择器无关

$(document).on('click','.foo', function() {
    var dataIndex = $(this).data('index');
    $('.container div[data-index="'+dataIndex+'"]').addClass('bah');
}); 
Javascript:

$(document).on('click','.foo', function() {
        $(this).addClass('bah');
});
HTML:


项目1

项目2

项目1

项目2

Fiddle示例:

您可以使用
.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');
});