从一个div中选择数据属性,将类添加到具有相同数据属性值的另一个div [英] Select data attribute from one div, add class to another div which has same data attribute value
本文介绍了从一个div中选择数据属性,将类添加到具有相同数据属性值的另一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$("#devMap div").click(function(){
var data = $(this).attr('data-name');
alert(data); //this is getting the correct data-name value
if($('#accordian .blocks').data('name')===data){
$(this).toggleClass('active'); // i want this to add the class active to the #accordian .blocks which has the data-name equal to the #devMap div data-name value
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="devMap">
<div class="toggleAccordian" data-name="block1"></div>
<div class="toggleAccordian" data-name="block2"></div>
</div>
<div id="accordian">
<div class="blocks" data-name="block1"></div>
<div class="blocks" data-name="block2"></div>
</div>
我希望当用户单击on #devMap .toggleAccordian
时,它会在#accordian
下的同一data-name属性上切换类,我尝试了此操作:
I want that when a user clicks on #devMap .toggleAccordian
it toggles a class on the same data-name attribute under #accordian
, I tried this:
推荐答案
您可以使用属性等于选择器,以获取所有具有属性data-name等于当前数据名称的.block
元素:
You can use attribute equal selector to get all .block
elements having attribute data-name equal to current data name:
$('#accordian .blocks[data-name="'+data+'"]').toggleClass('active');
这篇关于从一个div中选择数据属性,将类添加到具有相同数据属性值的另一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文