Adding class to element with matching custom data

2020-07-11 10:03发布

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

I think I'm doing something wrong.

FIDDLE

标签: jquery
3条回答
Fickle 薄情
2楼-- · 2020-07-11 10:17

Change:

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

To:

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

And if any of the data is being inserted or changed dynamically, you may consider using:

$('section').filter(function() { 
    return $(this).data('my-element') == myEm;
}).addClass('clicked');
查看更多
淡お忘
3楼-- · 2020-07-11 10:24

Try this:

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

You are also missing:

); after } at the end of your code

JSFiddle Demo

查看更多
爷、活的狠高调
4楼-- · 2020-07-11 10:24

Change -

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

to this -

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

or this

var myEm = $(this).data('my-element');
查看更多
登录 后发表回答