Reputation: 10671
How do I get the data-attr
of the SELECTED a
using jquery when the click handler is bound to it's outer div?
<ul class="js-click">
<li><a href="" data-attr="hello">Hello</a></li>
<li><a href="" data-attr="world">World</a></li>
</ul>
$('.js-click').on('click', function(e) {
});
The restriction here is that I have to bind the click on the <ul>
Upvotes: 2
Views: 2104
Reputation: 2802
//this would bind a handler that would execute anytime the ul is clicked
$('.js-click').on('click', function(e) { });
You're asking two questions. How to bind a handler, and then how to access the data attribute.
Binding the handler
You're close to binding the handler to your js-click
class, but you can get more granular by adding a filter.
Refer to the jQuery docs for more info.
$('.js-click').on([event], [filter], [handler]);
//Bind a handler to js-click, but only execute for <a> elements
$('.js-click').on('click', 'a', function(e) { });
Accessing that data attribute
By including the data-
prefix on the attribute, you're telling jQuery to cache the value automatically when it's ready.
Refer to jQuery data docs for more info
<a href="" data-attr="hello">Hello</a>
would be equivalent to
$('a').data('attr', 'hello');
To access the data, you just need to use the key, which in this case would be attr
. It's worth noting that you could access the attribute directly, but use one or the other (preferably .data
).
e.g. with your markup..
<a href="" data-attr="hello">Hello</a>
$('.js-click').on('click', 'a', function(e) {
var $this = $(this);
$this.data('attr', 'I changed');
//what will the value be? It's going to be 'Hello', because we're accessing the attribute in the DOM
alert($this.attr('data-attr'));
//what will the value be? It's going to be 'I changed', because we're accessing the data cache
alert($this.data('attr'));
});
Put them together and you can do this.
$('.js-click').on('click', 'a', function(e) {
var data = $(this).data('attr');
//quick sanity check to make sure the attribute exists
if(typeof data !== 'undefined') {
//do stuff
}
});
Upvotes: 0
Reputation: 5038
You can access the target <a>
with e.target
from the click event
$('.js-click').on('click', 'a', function(e) {
var data = $(e.target).data("attr");
});
Upvotes: 1
Reputation: 5953
You can do it like this:
$('.js-click').on('click','a', function(e) {
var data=$(this).data('attr');
});
Listen for click on anchor
Upvotes: 1