使用匹配的自定义数据属性向元素添加类

时间:2014-07-28 17:15:34

标签: jquery

我有自定义数据属性的元素列表。当被点击元素的数据属性与该元素的数据属性匹配时,我需要能够在点击时向另一个元素添加一个类。

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');
});

我认为我做错了什么。

FIDDLE

3 个答案:

答案 0 :(得分:16)

试试这个:

$('div').click(function() {
    var myEm = $(this).attr('data-my-element');
    //alert(myEm);
    $('section[data-my-element = '+myEm+']').addClass('clicked');
});

你也失踪了:

在代码末尾的);之后

}

<强> JSFiddle Demo

答案 1 :(得分:3)

变化:

 var myEm = $(this).val('data-my-element'); 

要:

 var myEm = $(this).data('my-element');

如果动态插入或更改任何数据,您可以考虑使用:

$('section').filter(function() { 
    return $(this).data('my-element') == myEm;
}).addClass('clicked');

答案 2 :(得分:0)

改变 -

var myEm = $(this).val('data-my-element'); //doesn't have a value

到此 -

var myEm = $(this).attr('data-my-element'); // returns the value of the custom attribute

或者

var myEm = $(this).data('my-element');
相关问题