2013-08-23 78 views
0

我有一个DOM树是这样的:获取正确的元素

<div class="like-bttn" data-answer-id="{{answer.id}}"> 
    <div class="count>{{ answer.like_score }}</div> 
    <div class="heart>&#10084;</div> 
</div> 

我有一个JavaScript代码,以使Ajax请求的时候像-BTTN点击:

$(".like-bttn").click(function(ev) { 
    var id = $(ev.target).attr('data-answer-id'); 
    ... do something with id ... 
    }) 

但是当。心点击我的代码不起作用,因为ev.target是.heart,它没有'data-answer-id'

什么是正确的方法在这stiuation?

+0

我建议阅读http://learn.jquery.com/events/event-basics /和其他活动文章。 –

回答

2

使用$(this),不活动对象:

$(".like-bttn").click(function(ev) { 
    var id = $(this).attr('data-answer-id'); 
    ... do something with id ... 
}) 

,正如尼尔指出,它的清洁剂使用data

var id = $(this).data('answerId'); 
+1

或:'$(this).data('answerId')' – Neal

+0

jQuery将数据元素更改为camelCase。 [[source](http://api.jquery.com/data/#data-html5)] – Neal

+0

@Neal:实际上不是这样做的jQuery(或许它确实如此,但它都符合规范): http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes。 –