JavaScript event.target only reports child (MooTools)
I seem to get something fundamentally wrong. I have this HTML
<div id="thumbnails">
<a href="#image-0">
<开发者_StackOverflowimg src="blabla-1.jpg" />
</a>
<a href="#image-0">
<img src="blabla-1.jpg" />
</a>
<a href="#image-0">
<img src="blabla-1.jpg" />
</a>
</div>
and this JavaScript (MooTools library in use)
document.id('thumbnails').getElements('a').each(function(image_link, image_link_index)
{
image_link.addEvent('click', function(evt)
{
if (evt.target.get('tag') == 'a')
{
evt.stop();
console.log('a tag', evt.target);
}
console.log(':-(', evt.target);
});
});
Strangely I never get to that a element. I'm sure I'm misunderstanding something basic here.
You can play around with the code at http://jsfiddle.net/maryisdead/kHBE3/8/
why are you reinventing the wheel? event delegation is not something to be taken lightly - and you should use the built-in event-delegation (since 1.4.1) http://mootools.net/docs/core/Element/Element.Delegation
your code would change to:
document.id('thumbnails').addEvent('click:relay(a)', function(evt, el) {
evt.stop();
console.log(':-)', el.get("tag") == 'a', this.get("tag") == 'a');
});
where the relay()
pseudo can take any selector you like - eg. a.foo or a[href=#]
keep in mind that in 1.2 the event delegation was sort of experimental and somewhat less than perfect - when it came to mouseover:relay()
or focus:relay(input[type=text])
you can get some unexpected results in different browsers - issues addressed in 1.3.2 iirc. Also, change
events on checkboxes and radios in old ie6/7/8 revert to onpropertychange and may not bubble.
in any case, yours fails to come through to the anchor link as the event.target
as the event itself BUBBLES from the top down. i.e. it will start from img > a > thumbnails
but it won't raise different events for both - it will be the same event.target
on both all 3 elements yet -> this === a
what you can do though is console.log(this.get("tag") === 'a')); // true
- even though the initial target was the child of this
If you're going to use event
inside your code, you need to have the argument named event
, not evt
. Fix that, and you should be good to go.
I have no idea why it doesn't work. The event is firing on the image inside the link, not the link itself which is just flat out weird.
The only thing I can suggest (it doesn't fix it) is an easier way to select the elements.
$$('#thumbnails > a').each(...
I also just tried rewriting the same code to use my own toolkit, which is jQuery like. It still has the same problem, which means it's something JavaScript specific, not MooTools specific.
You could try if (evt.target.parentNode.get('tag') == 'a')
精彩评论