将类添加到具有匹配的自定义数据属性的元素 [英] Adding class to element with matching custom data attribute
本文介绍了将类添加到具有匹配的自定义数据属性的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有自定义数据属性"的元素列表.当被单击元素的数据属性与该元素的数据属性匹配时,我需要能够在单击时向另一个元素添加类.
I have a list of elements with Custom Data Attributes. I need to be able to add a class to another element on click when the data attribute of a clicked element matches the data attribute of that element.
HTML
<div data-my-element="value1">click 1</div>
<div data-my-element="another">click 2</div>
<div data-my-element="oneMore">click 3</div>
<section data-my-element="value1"></section>
<section data-my-element="another"></section>
<section data-my-element="oneMore"></section>
JS
$('div').click(function() {
var myEm = $(this).val('data-my-element');
$('section[data-my-element = '+myEm+']').addClass('clicked');
});
我认为我做错了事.
推荐答案
尝试一下:
$('div').click(function() {
var myEm = $(this).attr('data-my-element');
//alert(myEm);
$('section[data-my-element = '+myEm+']').addClass('clicked');
});
您还失踪了:
);
JSFiddle Demo
这篇关于将类添加到具有匹配的自定义数据属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文