| Page 1 of 1 | [ 4 posts ] |
|
Does anyone have an example of using Event Delegation with nested elements?
Example: Code: <table id="mylist"><tr id="msg_2"><td>asdf asdf asdf <a href="#" id="del_2">delete</a></td></tr></table> <script> var onMyClick = function (event, matchedEl, container) { alert(matchedEl.id); } Event.delegate("mylist","click",onMyClick,"a"); Event.delegate("mylist","click",onMyClick,"tr"); </script> If the anchor tag is clicked on I want to prevent the click event for TR from being called. Any help or insight is greatly appreciated. |
|
You have to cancel your event.
However the following is a little bit nicer. Code: <table id="mylist"> <tr id="msg_2"> <td> <span>asdf asdf asdf</span> <a href="#" id="del_2">delete</a> </td> </tr> </table> <script> var onMyClick = function (event, matchedEl, container) { alert(matchedEl.id); } Event.delegate("mylist","click",onMyClick,"a"); Event.delegate("mylist","click",onMyClick,"td>span"); </script> |
|
Thanks Mitch. I've tried the stopEvent(e) method but it did not help. I still get two alerts with the click on the anchor tag.
A more detailed example of the table: Code: <table id="mylist"> <tr id="msg_2"> <td><img src="/userPic.jpg"></td> <td> <div>UserName <a href="#" id="del_2">delete</a> </div> <div class="msgSnippet">asdf asdf asdf asdf asdf</div> </td> </tr> </table> <script> var onMyClick = function (event, matchedEl, container) { Event.stopEvent(event); alert(matchedEl.id); } Event.delegate("mylist","click",onMyClick,"a"); Event.delegate("mylist","click",onMyClick,"tr"); </script> |
|
I've actually got this to work. Here's what I came up with:
Code: <table id="mylist"> <tr id="msg_2"> <td><img src="/userPic.jpg"></td> <td> <div>UserName <a href="#" id="del_2">delete</a> </div> <div class="msgSnippet">asdf asdf asdf asdf asdf</div> </td> </tr> </table> <script type="text/javascript"> (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event; var onMyClick = function (event, matchedEl, container) { var tar = Event.getTarget(event); if (tar.tagName.toLowerCase() == 'a') { alert(tar.id); } else if (matchedEl.tagName.toLowerCase() == 'tr') { alert(matchedEl.id); } }; Event.delegate("mylist", "click", onMyClick, "tr"); })(); </script> |
| Page 1 of 1 | [ 4 posts ] |
| You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum |
© 2006-2013 Yahoo! Inc. All rights reserved.
All code on this site is licensed under the BSD License unless stated otherwise.
About This Site · Security Contact Info
Powered by phpBB® Forum Software © phpBB Group