Issue: YUI3 - Onclick event handling for links having same classes
We have few links in the page having same class. When I click on one of the links there are some different actions to be taken based on the which link was clicked, For e.g.
<a href="?page=1" data="test1" class="sample">One</a>
<a href="?page=2" data="test2" class="sample">two</a>
<a href="?page=3" data="test3" class="sample">three</a>
handler code:
Y.all('.sample').on('click', function(e){
e.preventDefault();
alert(this.getAttribute("data"));
});
when I click any of the links I get the list of all "data" attribute. We only need the data of link clicked.
all
gives you a list of matched elements. You can use each
to iterate through the list and do stuff for individual node. Refer to their Node Class API for more information.
Here is the code, and an example on jsfiddle.
Y.all('.sample').each(function(node) {
node.on('click', function(e) {
e.preventDefault();
alert(node.getAttribute("data"));
});
});
There is also a FAQ entry for this question in the Event user guide on yuilibrary.com (http://yuilibrary.com/yui/docs/event/#nodelist-this). It's generally preferable to use event delegation.