最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Meteor events target behaving strange on links with inner icons - Stack Overflow

programmeradmin0浏览0评论

Folks, I am confused with Meteor's event targets: Let's say I have two links, one with an icon (here: Font Awesome) inside, one with a simple "x" instead:

myTemplate.html

<a href="#" id="linkA" data-id="link"><i data-id="icon" class="icon-remove icon-white"></i></a>
<a href="#" id="linkB" data-id="link">x</a>

and I am using a click event on each, both events are just the same:

myTemplate.js

Template.myTemplate.events({
    'click #linkA': function(event,template) {
        event.preventDefault();
        console.log(event.target.getAttribute("data-id"));
    },
    'click #linkB': function(event,template) {
        event.preventDefault();
        console.log(event.target.getAttribute("data-id"));
    }
}

then I would expect them both to behave just the same. Instead, linkA's event gives me "icon" to the console, which is the data-id of the icon, and linkB's event brings me "link" to the console, which is the data-id of the link. I would expect the latter for both.

Any ideas what causes this behavior?

Folks, I am confused with Meteor's event targets: Let's say I have two links, one with an icon (here: Font Awesome) inside, one with a simple "x" instead:

myTemplate.html

<a href="#" id="linkA" data-id="link"><i data-id="icon" class="icon-remove icon-white"></i></a>
<a href="#" id="linkB" data-id="link">x</a>

and I am using a click event on each, both events are just the same:

myTemplate.js

Template.myTemplate.events({
    'click #linkA': function(event,template) {
        event.preventDefault();
        console.log(event.target.getAttribute("data-id"));
    },
    'click #linkB': function(event,template) {
        event.preventDefault();
        console.log(event.target.getAttribute("data-id"));
    }
}

then I would expect them both to behave just the same. Instead, linkA's event gives me "icon" to the console, which is the data-id of the icon, and linkB's event brings me "link" to the console, which is the data-id of the link. I would expect the latter for both.

Any ideas what causes this behavior?

Share Improve this question asked Sep 14, 2013 at 18:32 Moritz WalterMoritz Walter 7175 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Use event.currentTarget instead of event.target and it'll work, and learn how to deal with nested events and event bubbling

So, what we have here is event bubbling. It's javascript issue, not meteor's.

In the first case, you actually click <i> element, and that event is bubbling to its parents, and since #linkA parent has click handler it logs event.target (which is <i>) data-id attribute.

You can read more about this here

发布评论

评论列表(0)

  1. 暂无评论