Since .live() is just delegating events, place the handler on the closest element to be added.
var container = document.getElementById('my_container'); container.onclick = function(e) { e = e || window.event; var target = e.target || e.srcElement; while(target && target.nodeName.toUpperCase() !== 'LI' ) { if( target === this ) target = null; else target = target.parentNode; } if( target ) {
It also looks like .live() in the sense that it searches from e.target to the delegate container to see if it is your target element.
Just testing e.target itself e.target not enough if li has children.
For a more complex analysis of elements, you can use .matchesSelector , although you need to bind it to HTMLElement.prototype under the correct name, since most browsers include it as an extension.
In addition, you will need a patch for IE8, but it is quite easy.
if (HTMLElement) { if (!HTMLElement.prototype.matches && !HTMLElement.prototype.matchesSelector) { HTMLElement.prototype.matches = HTMLELement.prototype.matchesSelector = HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelecvtor || HTMLElement.prototype.msMatchesSelector || HTMLElement.prototype.oMatchesSelector; } } else if (!Element.prototype.matchesSelector && Element.prototype.querySelectorAll) { Element.prototype.matches = Element.prototype.matchesSelector = function() { // exercise for reader to implement using .querySelectorAll, // though it pretty easy, and available online if you search } }
user1106925
source share