How do I reference data from a parent element using jQuery?
I would like to reference the data-post-id of a parent div when clicking on an achor:
<div data-post-id="5">
<a data-vote-type="1">Like</a>
<a data-vote-type="2">Dislike</a>
</div>
To reference the vote-type, I can do this:
var voteData = '&voteType=' + $(this).data('vote-type')
But I would also like to include the post-id in the开发者_高级运维 voteData
var. I'm not sure how to do this however. I have multiple posts on the page, each with their own like/dislike buttons!
You're looking for $(this).parent()
.
If you need a specific ancestor, you should call $(this).closest('selector')
, which finds the innermost ancestor that matches a selector.
var voteData = '&voteType=' + $(this).data('vote-type') + '&postId=' + $(this).parent().data('post-id');
精彩评论